﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Globalization;
using Newtonsoft.Json;
using log4net.Core;
using System.Data;
using System.Threading;
using NPOI.SS.Formula.Functions;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.IO;
using OfficeOpenXml;
using DirectShowLib;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using ET_DbCommon;
using OfficeOpenXml.Style;
using static NPOI.HSSF.Util.HSSFColor;
using OfficeOpenXml.DataValidation;
using ET_DbCommon.Model;
using ET_DbCommon.DAL;
using System.Diagnostics;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using System.Windows.Media.TextFormatting;
using System.Configuration;
using WPFMediaKit.DirectX;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using System.Reflection;

namespace ET.ScoreTeacherClient.Views
{
    /// <summary>
    /// TestPaper.xaml 的交互逻辑
    /// </summary>
    public partial class TestPaper : UserControl, INotifyPropertyChanged
    {
        public TestPaper()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        public bool IsSelected = false;//指示当前是否需要筛选试卷
        public bool StepCanCopyflag = false;//指示步骤是否启用复制功能
        public bool TaskCanCopyflag = false;//指示任务是否启用复制功能
        public List<TestQuestionTaskViewModel> Tasksneedcopy = new List<TestQuestionTaskViewModel>();
        public List<TestQuestionTaskViewModel> TaskTocopy = new List<TestQuestionTaskViewModel>();
        public List<TestQuestionTaskStepViewModel> Stepsneedcopy = new List<TestQuestionTaskStepViewModel>();
        public ObservableCollection<PublicParameter> TaskDevStateList { get; set; } = new ObservableCollection<PublicParameter>();

        public ObservableCollection<TrainPositionParameter> TaskTrainPositionList { get; set; } = new ObservableCollection<TrainPositionParameter>();
        public ObservableCollection<BeforeStepParameter> TaskBeforeList { get; set; } = new ObservableCollection<BeforeStepParameter>();

        //public ObservableCollection<PublicParameter> StepDevStateList { get; set; } = new ObservableCollection<PublicParameter>();
        //public ObservableCollection<TrainPositionParameter> StepTrainPositionList { get; set; } = new ObservableCollection<TrainPositionParameter>();
        //public ObservableCollection<BeforeStepParameter> StepBeforeList { get; set; } = new ObservableCollection<BeforeStepParameter>();
        //public ObservableCollection<IntervalMonitorParameter> StepIntervalMonitorList { get; set; } = new ObservableCollection<IntervalMonitorParameter>();
        public PrerequisiteJson PrerequisiteJson { get; set; } = new PrerequisiteJson();
        //public List<Device> TrainList { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.列车];
        //public List<Device> AreaList { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.计轴区段];
        //public List<Device> MyStation { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.车站];//获取所有车站 Modify by lukun

        //初始化语音库--Add by lukun

        private List<PaperModel> m_QueryPaperList = new List<PaperModel>();


        //加载线路信息--Add by peizhankun
        private string RefLineName = System.Configuration.ConfigurationManager.AppSettings["Linename"];
        //开放全部线路信息
        private bool DebugAllLine = false;

        private readonly object lineBlock = new object();


        public static List<TestQuestionTaskStepViewModel> TestQuestionTaskStepList { get; set; } = new List<TestQuestionTaskStepViewModel>();//当前场景全部作业步骤 Add by gy
        public List<PaperModel> QueryPaperList
        {
            get
            {
                return this.m_QueryPaperList;
            }
            set
            {
                this.m_QueryPaperList = value;
                this.OnPropertyChanged();
            }
        }
        #region SelectedTestPaper
        private TestPaperViewModel m_SelectedTestPaper;

        public TestPaperViewModel SelectedTestPaper
        {
            get
            {
                return this.m_SelectedTestPaper;
            }
            set
            {
                this.m_SelectedTestPaper = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        #region SelectedTestQuestion
        private TestQuestionViewModel m_SelectedTestQuestion;

        public TestQuestionViewModel SelectedTestQuestion
        {
            get
            {
                return this.m_SelectedTestQuestion;
            }
            set
            {
                this.m_SelectedTestQuestion = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        #region SelectedTestQuestion
        private voicelibraryViewModel m_SelectedVoicelibrary;

        public voicelibraryViewModel SelectedVoicelibrary
        {
            get
            {
                return this.m_SelectedVoicelibrary;
            }
            set
            {
                this.m_SelectedVoicelibrary = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        #region SelectedTestQuestionTask
        private TestQuestionTaskViewModel m_SelectedTestQuestionTask;

        public TestQuestionTaskViewModel SelectedTestQuestionTask
        {
            get
            {
                return this.m_SelectedTestQuestionTask;
            }
            set
            {
                this.m_SelectedTestQuestionTask = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        #region SelectedTestQuestionTaskStep
        private TestQuestionTaskStepViewModel m_SelectedTestQuestionTaskStep;

        public TestQuestionTaskStepViewModel SelectedTestQuestionTaskStep
        {
            get
            {
                return this.m_SelectedTestQuestionTaskStep;
            }
            set
            {
                this.m_SelectedTestQuestionTaskStep = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        #region PaperList
        private ObservableCollection<TestPaperViewModel> m_PaperList = new ObservableCollection<TestPaperViewModel>();

        public ObservableCollection<TestPaperViewModel> PaperList
        {
            get
            {
                return this.m_PaperList;
            }
            set
            {
                this.m_PaperList = value;
                this.OnPropertyChanged();
            }
        }

        #endregion

        #region QuestionList
        private ObservableCollection<TestQuestionViewModel> m_QuestionList = new ObservableCollection<TestQuestionViewModel>();

        public ObservableCollection<TestQuestionViewModel> QuestionList
        {
            get
            {
                return this.m_QuestionList;
            }
            set
            {
                this.m_QuestionList = value;
                ShowQuestionList = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        private ObservableCollection<TestQuestionViewModel> m_ShowQuestionList = new ObservableCollection<TestQuestionViewModel>();

        public ObservableCollection<TestQuestionViewModel> ShowQuestionList
        {
            get
            {
                return this.m_ShowQuestionList;
            }
            set
            {
                this.m_ShowQuestionList = value;
                this.OnPropertyChanged();
            }
        }
        #region AllQuestionList
        private ObservableCollection<TestQuestionViewModel> m_AllQuestionList = new ObservableCollection<TestQuestionViewModel>();

        public ObservableCollection<TestQuestionViewModel> AllQuestionList
        {
            get
            {
                return this.m_AllQuestionList;
            }
            set
            {
                this.m_AllQuestionList = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        #region TestQuestionTaskList
        private ObservableCollection<TestQuestionTaskViewModel> m_TestQuestionTaskList { get; set; } = new ObservableCollection<TestQuestionTaskViewModel>();
        public ObservableCollection<TestQuestionTaskViewModel> TestQuestionTaskList
        {
            get
            {
                return m_TestQuestionTaskList;
            }
            set
            {
                this.m_TestQuestionTaskList = value;
                this.OnPropertyChanged();
            }
        }
        #endregion

        #region VoicelibraryList
        private ObservableCollection<voicelibraryViewModel> m_VoicelibraryViewList { get; set; } = new ObservableCollection<voicelibraryViewModel>();
        public ObservableCollection<voicelibraryViewModel> VoicelibraryViewList
        {
            get
            {
                return m_VoicelibraryViewList;
            }
            set
            {
                this.m_VoicelibraryViewList = value;
                this.OnPropertyChanged();
            }
        }
        #endregion


        #region ManageMode
        private bool m_ManageMode = true;

        public bool ManageMode
        {
            get
            {
                this.colChoose.Visibility = this.m_ManageMode ? Visibility.Collapsed : Visibility.Visible;
                return this.m_ManageMode;
            }
            set
            {
                this.m_ManageMode = value;
                this.OnPropertyChanged();
            }
        }
        #endregion
        List<PaperModel> paperList = new List<PaperModel>();
        #region INotifyPropertyChanged 接口实现
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propName = null)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
        /// <summary>
        /// 加载窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {

            OperateItemModels = ET_DbCommon.DAL.OperateItemDAL.GetOperateItems();
            DeviceTypeModels = ET_DbCommon.DAL.Device_TypeDAL.GetDeviceType();
            DeviceModels = ET_DbCommon.DAL.DeviceDAL.GetDevice();
            PostModels = ET_DbCommon.DAL.PostDAL.GetPostInfo();
            this.RefDate();
            InitTestVisibleLineComboBox();
            InitTestVisibleStationComboBox();

            Task.Run(new Action(() =>
            {
                while (true)
                {
                    while (IsSelected)
                    {
                        try
                        {
                            this.Dispatcher.Invoke(new Action(() =>
                            {
                                if (this.SearchPaperName.Text == "")
                                {
                                    QueryPaperList = PaperDAL.GetAll();
                                    this.PaperList.Clear();
                                    foreach (var model in QueryPaperList)
                                    {
                                        this.Dispatcher.BeginInvoke(new Action(() =>
                                        {
                                            if (this.PaperList.Where(p => p.Id == model.Id).Count() == 0)
                                                this.PaperList.Add(new TestPaperViewModel(model));
                                        }));
                                    }
                                }
                                else
                                {
                                    this.PaperList.Clear();
                                    foreach (var model in QueryPaperList)
                                    {
                                        this.Dispatcher.BeginInvoke(new Action(() =>
                                        {
                                            if (this.PaperList.Where(p => p.Id == model.Id).Count() == 0)
                                                this.PaperList.Add(new TestPaperViewModel(model));
                                        }));
                                    }
                                }
                            }));
                        }
                        catch (Exception ex)
                        {

                        }
                        Thread.Sleep(1000);
                    }
                    Thread.Sleep(1000);

                }

            }));
            //加载时显示筛选线路中的初始值
            var TestLine = System.Configuration.ConfigurationManager.AppSettings["LineName"];
            this.InitTestLineSelect(TestLine);
            this.InitTestStationSelect();

        }
        #endregion

        public void InitTestStationSelect()
        {

        }

        /// <summary>
        /// 初始化车站筛选列表
        /// </summary>
        public void InitTestVisibleStationComboBox()
        {
            lock (lineBlock)
            {
                this.TestVisibleStationComboBox.Items.Add("全部");
                foreach (var station in MainWindowNew.DeviceList[5])
                {
                    if (station.LineName == RefLineName)
                    {
                        this.TestVisibleStationComboBox.Items.Add(station.DeviceName);
                    }
                }
            }

        }

        /// <summary>
        /// 初始化筛选列表 add by peizhankun
        /// </summary>
        private void InitTestVisibleLineComboBox()
        {
            this.TestVisibleLineComboBox.Items.Add("全部");
            var allLineName = Enum.GetValues(typeof(LineNameEnum));

            foreach (LineNameEnum lineName in allLineName)
            {
                this.TestVisibleLineComboBox.Items.Add(GetLineNameAttribute(lineName));
            }
        }

        /// <summary>
        /// 新建试卷
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnNewPaper_Click(object sender, RoutedEventArgs e)
        {
            PaperModel paperModel = new PaperModel();
            Paper paper = new Paper(paperModel);
            //paper.ShowDialog();
            if (paper.ShowDialog() == true)
                this.PaperList.Add(new TestPaperViewModel(paperModel));
        }
        /// <summary>
        /// 修改试卷
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnModify_Click(object sender, RoutedEventArgs e)
        {
            if (this.SelectedTestPaper == null)
                return;
            PaperModel paperModel = new PaperModel();
            paperModel.Id = SelectedTestPaper.Id;
            paperModel.Level = SelectedTestPaper.Level;
            paperModel.Describes = SelectedTestPaper.Describes;
            paperModel.TesquestiontList = SelectedTestPaper.TesQuestiontList;
            Paper paper = new Paper(paperModel);
            if (paper.ShowDialog() == true)
            {
                SelectedTestPaper.Level = paperModel.Level;
                SelectedTestPaper.Describes = paperModel.Describes;
                SelectedTestPaper.UpdateTime = paperModel.UpdateTime;
                SelectedTestPaper.TesQuestiontList = paperModel.TesquestiontList;
            }
        }
        /// <summary>
        /// 线路选择栏默认值筛选 add by peizhankun
        /// </summary>
        private void InitTestLineSelect(string TestLine)
        {
            // 使用 Dispatcher.Invoke 确保在 UI 线程中设置 SelectedItem
            TestVisibleLineComboBox.Dispatcher.Invoke(() =>
            {
                //转换配置文件中的LineName字段为LineNameEnum枚举类型
                if (Enum.TryParse(TestLine, out LineNameEnum tryLine))
                {
                    switch (tryLine)
                    {
                        case LineNameEnum.BeiJing9:
                            TestVisibleLineComboBox.Text = GetLineNameAttribute(LineNameEnum.BeiJing9); // 北京9号线
                            break;
                        case LineNameEnum.FangShan:
                            TestVisibleLineComboBox.Text = GetLineNameAttribute(LineNameEnum.FangShan); // 房山线
                            break;
                        case LineNameEnum.BaTong:
                            TestVisibleLineComboBox.Text = GetLineNameAttribute(LineNameEnum.BaTong); // 1-八通线
                            break;
                        case LineNameEnum.BeiJingS1:
                            TestVisibleLineComboBox.Text = GetLineNameAttribute(LineNameEnum.BeiJingS1); // 北京S1
                            break;
                        default:
                            TestVisibleLineComboBox.Text = "全部"; // 全部
                            break;
                    }
                }
                else
                {
                    TestVisibleLineComboBox.Text = "全部"; // 全部
                }

            });

        }

        /// <summary>
        /// 删除试卷
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (this.SelectedTestPaper != null && MessageBox.Show("确定删除试卷？", "询问", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                if (PaperDAL.Delete(this.SelectedTestPaper.Id) > 0)
                {
                    this.PaperList.Remove(this.SelectedTestPaper);
                }
            }
        }
        /// <summary>
        /// 试卷列表单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DgGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.SelectedTestPaper != null)
            {
                this.QuestionList.ToList().ForEach(p =>
                {
                    p.IsChecked = false;
                });
                if (string.IsNullOrEmpty(SelectedTestPaper.TesQuestiontList))
                    return;

                var TesQuestiontId = SelectedTestPaper.TesQuestiontList.Split(',').ToList();
                for (int i = 0; i < TesQuestiontId.Count(); i++)
                {
                    if (QuestionList.Any(x => x.Id == int.Parse(TesQuestiontId[i])))
                    {
                        this.QuestionList.FirstOrDefault(x => x.Id == int.Parse(TesQuestiontId[i])).IsChecked = true;
                    }
                }
            }

        }


        /// <summary>
        /// 刷新
        /// </summary>
        private void RefDate()
        {
            Task.Run(() =>
            {
                //试卷列表
                paperList = PaperDAL.GetAll();
                List<Paper_TestQuestionModel> questionList = Paper_TestQuestionDAL.GetAll();
                var deviceList = DeviceDAL.GetDeviceByLine(RefLineName);
                var AlldeviceList = DeviceDAL.GetDevice();
                var DicDevType = Device_TypeDAL.GetDeviceType().ToDictionary(t => t.Id, t => t.DeviceType);
                lock (lineBlock)
                {
                    if (DebugAllLine)
                    {
                        MainWindowNew.DeviceList.Clear();
                        foreach (var k in DicDevType)
                        {
                            MainWindowNew.DeviceList.Add(k.Key, AlldeviceList.FindAll(p => p.DeviceTypeId == k.Key));
                        }
                    }
                    else
                    {
                        MainWindowNew.DeviceList.Clear();
                        foreach (var k in DicDevType)
                        {
                            MainWindowNew.DeviceList.Add(k.Key, deviceList.FindAll(p => p.DeviceTypeId == k.Key));
                        }
                    }
                }



                foreach (var model in paperList)
                {
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        if (this.PaperList.FirstOrDefault(p => p.Id == model.Id) == null)
                        {
                            var paperView = new TestPaperViewModel(model);



                            //筛选指定线路试卷 add by peizhankun   **仅限于北京运二**
                            if (this.RefLineName == LineNameEnum.BeiJing9.ToString() && paperView.Describes.Contains(GetLineNameAttribute(LineNameEnum.BeiJing9)))
                            {
                                this.PaperList.Add(paperView);

                            }
                            else if (this.RefLineName == LineNameEnum.FangShan.ToString() && paperView.Describes.Contains(GetLineNameAttribute(LineNameEnum.FangShan)))
                            {
                                this.PaperList.Add(paperView);

                            }
                            else if (this.RefLineName == LineNameEnum.BaTong.ToString() && paperView.Describes.Contains(GetLineNameAttribute(LineNameEnum.BaTong)))
                            {
                                this.PaperList.Add(paperView);

                            }
                            else if (this.RefLineName == LineNameEnum.BeiJingS1.ToString() && paperView.Describes.Contains(GetLineNameAttribute(LineNameEnum.BeiJingS1)))
                            {
                                this.PaperList.Add(paperView);

                            }
                            else
                            {
                                //检测名称中不包含四条线名称的试卷添加到显示列表中
                                //如果存在DebugAllLine，将其加到判断条件中 可以开放全部试卷
                                if (DebugAllLine
                                || !paperView.Describes.Contains(GetLineNameAttribute(LineNameEnum.BeiJing9))
                                && !paperView.Describes.Contains(GetLineNameAttribute(LineNameEnum.FangShan))
                                && !paperView.Describes.Contains(GetLineNameAttribute(LineNameEnum.BaTong))
                                && !paperView.Describes.Contains(GetLineNameAttribute(LineNameEnum.BeiJingS1)))
                                {
                                    this.PaperList.Add(paperView);
                                }

                            }
                        }
                    }));
                }

                foreach (var model in questionList)
                {
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        if (this.QuestionList.FirstOrDefault(x => x.Id == model.Id) == null)
                        {
                            var questionView = new TestQuestionViewModel(model);
                            this.QuestionList.Add(questionView);
                            this.AllQuestionList.Add(questionView);

                            //筛选指定线路场景 add by peizhankun   **仅限于北京运二**
                            if (this.RefLineName == LineNameEnum.BeiJing9.ToString() &&
                            questionView.TestName.Contains(GetLineNameAttribute(LineNameEnum.BeiJing9)))
                            {
                                this.ShowQuestionList.Add(questionView);
                            }
                            else if (this.RefLineName == LineNameEnum.FangShan.ToString() &&
                            questionView.TestName.Contains(GetLineNameAttribute(LineNameEnum.FangShan)))
                            {
                                this.ShowQuestionList.Add(questionView);
                            }
                            else if (this.RefLineName == LineNameEnum.BaTong.ToString() &&
                            questionView.TestName.Contains(GetLineNameAttribute(LineNameEnum.BaTong)))
                            {
                                this.ShowQuestionList.Add(questionView);
                            }
                            else if (this.RefLineName == LineNameEnum.BeiJingS1.ToString() &&
                            questionView.TestName.Contains(GetLineNameAttribute(LineNameEnum.BeiJingS1)))
                            {
                                this.ShowQuestionList.Add(questionView);
                            }
                            else
                            {
                                if (DebugAllLine
                                || !questionView.TestName.Contains(GetLineNameAttribute(LineNameEnum.BeiJing9))
                                && !questionView.TestName.Contains(GetLineNameAttribute(LineNameEnum.FangShan))
                                && !questionView.TestName.Contains(GetLineNameAttribute(LineNameEnum.BaTong))
                                && !questionView.TestName.Contains(GetLineNameAttribute(LineNameEnum.BeiJingS1)))
                                    this.ShowQuestionList.Add(questionView);
                            }
                            //switch (RefLineName.ToString())
                            //{
                            //    case "Beijing9":
                            //        this.ShowQuestionList.Add(questionView);
                            //        break;
                            //    case "FangShan":
                            //        this.ShowQuestionList.Add(questionView);
                            //        break;
                            //    case "1-BaTong":
                            //        this.ShowQuestionList.Add(questionView);
                            //        break;
                            //    case "BeijingS1":
                            //        this.ShowQuestionList.Add(questionView);
                            //        break;
                            //}


                        }

                    }));
                }
            });
        }

        private void BtnTiming_Click(object sender, RoutedEventArgs e)
        {
            Button button = e.OriginalSource as Button;
            switch (button.Content.ToString())
            {
                case "新建":
                    TestQuestionViewModel viewModel = new TestQuestionViewModel();
                    TestQuestionEdit testQuestionEdit = new TestQuestionEdit(viewModel, this.PaperList, this.QuestionList);
                    if (testQuestionEdit.ShowDialog() == true)
                        this.QuestionList.Add(viewModel);

                    break;
                case "修改":
                    if (this.SelectedTestQuestion == null)
                    {
                        return;
                    }
                    TestQuestionEdit testQuestionEdit1 = new TestQuestionEdit(this.SelectedTestQuestion, this.PaperList, this.QuestionList);
                    testQuestionEdit1.ShowDialog();
                    break;
                case "删除":
                    if (this.SelectedTestQuestion != null && MessageBox.Show("确定删除场景？", "询问", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        if (this.QuestionList.FirstOrDefault(p => p.AttachQuestion != null && p.AttachQuestion.Split(',').Contains(this.SelectedTestQuestion.Id.ToString())) != null)
                        {
                            MessageBox.Show("当前场景作为其他主场景的副场景，无法删除！");
                            return;
                        }
                        ET_DbCommon.DAL.Paper_TestQuestionDAL.Delete(this.SelectedTestQuestion.Id);

                    }
                    break;
                case "导入":
                    {
                        // 创建一个OpenFileDialog实例  
                        System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();

                        // 设置过滤条件，只显示Excel文件  
                        openFileDialog.Filter = "Excel Files (*.xls;*.xlsx)|*.xls;*.xlsx";
                        openFileDialog.Title = "Select an Excel File";

                        // 显示对话框，并检查用户是否选择了一个文件  
                        if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            string filePath = openFileDialog.FileName;

                            if (this.SelectedTestQuestion == null)
                            {
                                ReadExcelFile(filePath);
                            }
                            else
                            {
                                if (MessageBox.Show($"将覆盖{this.SelectedTestQuestion.TestName}场景,请确认!", "确认", MessageBoxButton.OKCancel, MessageBoxImage.Information) == MessageBoxResult.OK)
                                {
                                    ReadExcelFile(filePath, this.SelectedTestQuestion.Id);
                                }
                            }
                        }
                    }
                    break;
                case "导出":
                    {
                        if (this.SelectedTestQuestion != null)
                        {
                            SaveExcelFile(SelectedTestQuestion);
                        }
                        else
                        {
                            if (MessageBox.Show($"将保存所有场景,请确认!", "确认", MessageBoxButton.OKCancel, MessageBoxImage.Information) == MessageBoxResult.OK)
                            {
                                //SaveExcelFile();
                                SaveExcelFileByLine();
                            }
                            else if (MessageBox.Show("将保存所有场景的学员试卷", "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
                            {
                                SaveExcelFileByLineStudent();
                            }
                        }
                    }
                    break;
            }
        }

        #region 按线路导出试卷 北京运二
        private void SaveExcelFileByLine()
        {
            using (ExcelPackage package = new ExcelPackage())
            {
                List<postModel> roleModels = PostDAL.GetPostInfo();
                ExcelWorksheet menuSheet = package.Workbook.Worksheets.Add("目录");

                ObservableCollection<TestQuestionViewModel> papers = this.ShowQuestionList;
                menuSheet.Cells[1, 1].Value = "场景名称";
                menuSheet.Column(1).Width = 50;
                menuSheet.Cells[1, 1].Style.Font.Size = 20;
                menuSheet.Cells[1, 1].Style.Font.Bold = true;
                menuSheet.Cells[1, 2].Value = "包含岗位";
                menuSheet.Column(2).Width = 80;
                menuSheet.Cells[1, 2].Style.Font.Size = 20;
                menuSheet.Cells[1, 2].Style.Font.Bold = true;




                foreach (var selectedTestQuestion in ShowQuestionList)
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(selectedTestQuestion.TestName);

                    List<Paper_TestQuestion_TaskModel> taskList = Paper_TestQuestion_TaskDAL.GetMyPaper_TestQuestion_TaskModel(selectedTestQuestion.Id);
                    worksheet.Cells[1, 1].Value = selectedTestQuestion.TestName;
                    worksheet.Cells[$"A1:O1"].Merge = true;
                    worksheet.Row(1).Height = 50;
                    worksheet.Cells[1, 1].Style.Font.Size = 36;
                    worksheet.Cells[1, 1].Style.Font.Bold = true;
                    worksheet.Cells[1, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    string targetSheetName = "目录"; // 或者根据你的逻辑来设置sheet名

                    // 使用HYPERLINK函数设置超链接  
                    string hyperlinkFormula = $"=HYPERLINK(\"#'{targetSheetName}'!A1\", \"{selectedTestQuestion.TestName}\")";
                    worksheet.Cells[1, 1].Formula = hyperlinkFormula;
                    worksheet.Cells[1, 1].Style.Font.UnderLine = true;
                    worksheet.Cells[1, 1].Style.Font.Color.SetColor(System.Drawing.Color.Blue); // 设置为蓝色文本  

                    worksheet.Cells[2, 1].Value = selectedTestQuestion.Describes;
                    worksheet.Cells[$"A2:O2"].Merge = true;
                    worksheet.Row(2).Height = 30;
                    worksheet.Cells[2, 1].Style.Font.Size = 12;
                    worksheet.Cells[2, 1].Style.Font.Bold = true;
                    worksheet.Cells[2, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    for (int j = 1; j <= 15; j++)
                    {
                        worksheet.Column(j).Width = 20;
                        worksheet.Cells[3, j].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        worksheet.Cells[3, j].Style.Font.Size = 16;
                        worksheet.Cells[3, j].Style.Font.Bold = true;
                    }
                    worksheet.Column(5).Width = 30;
                    worksheet.Column(8).Width = 50;
                    worksheet.Column(15).Width = 50;

                    worksheet.Cells[3, 1].Value = "作业程序";
                    worksheet.Cells[3, 2].Value = "所属系统";
                    worksheet.Cells[3, 3].Value = "岗位";
                    worksheet.Cells[3, 4].Value = "步骤类型";
                    worksheet.Cells[3, 5].Value = "操作类型";
                    worksheet.Cells[3, 6].Value = "设备类型";
                    worksheet.Cells[3, 7].Value = "设备";
                    worksheet.Cells[3, 8].Value = "步骤内容";
                    worksheet.Cells[3, 9].Value = "参数";
                    worksheet.Cells[3, 10].Value = "关键词";
                    worksheet.Cells[3, 11].Value = "前置状态";
                    worksheet.Cells[3, 12].Value = "配分";
                    worksheet.Cells[3, 13].Value = "前提条件";
                    worksheet.Cells[3, 14].Value = "UIOrder";
                    worksheet.Cells[3, 15].Value = "是否为持续性判断";
                    int i = 4;
                    int k = 0;
                    foreach (Paper_TestQuestion_TaskModel task in taskList)
                    {
                        k++;

                        task.TestQuestionTaskSteps = Paper_TestQuestion_Task_StepDAL.GetMyPaper_TestQuestion_Task_StepModel(task.Id);
                        if (task.TestQuestionTaskSteps.Count < 1)
                        {
                            continue;
                        }
                        worksheet.Cells[i, 1].Value = task.Describes;
                        worksheet.Cells[$"A{i}:A{i + task.TestQuestionTaskSteps.Count - 1}"].Merge = true;
                        ExcelRange range = worksheet.Cells[$"A{i}:O{i + task.TestQuestionTaskSteps.Count - 1}"];
                        range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                        if (k % 2 == 0)
                        {
                            range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                        }
                        else
                        {
                            range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.White);

                        }

                        foreach (var step in task.TestQuestionTaskSteps.OrderBy(x => x.UIOrder))
                        {
                            ConvertToExcel(worksheet, step, i);
                            i++;
                        }
                    }

                    ExcelRange allRange = worksheet.Cells[$"A1:O{i}"];
                    allRange.Style.Border.Top.Style = ExcelBorderStyle.Thin; // 上边框  
                    allRange.Style.Border.Bottom.Style = ExcelBorderStyle.Thin; // 下边框  
                    allRange.Style.Border.Left.Style = ExcelBorderStyle.Thin; // 左边框  
                    allRange.Style.Border.Right.Style = ExcelBorderStyle.Thin; // 右边框  
                }


                //目录超链接
                for (int i = 0; i < papers.Count; i++)
                {
                    if (!string.IsNullOrEmpty(papers[i].TestName))
                    {
                        menuSheet.Cells[i + 2, 1].Value = papers[i].TestName;
                    }
                    if (!string.IsNullOrEmpty(papers[i].Roles))
                    {
                        menuSheet.Cells[i + 2, 2].Value = string.Join(",", papers[i].Roles.Split(',').ToList().Select(x => roleModels.FirstOrDefault(t => t.post_id == x).post_name));

                    }
                    string targetSheetName = papers[i].TestName; // 或者根据你的逻辑来设置sheet名  

                    // 使用HYPERLINK函数设置超链接  
                    string hyperlinkFormula = $"=HYPERLINK(\"#'{targetSheetName}'!A1\", \"{papers[i].TestName}\")";
                    menuSheet.Cells[i + 2, 1].Formula = hyperlinkFormula;
                    menuSheet.Cells[i + 2, 1].Style.Font.UnderLine = true;
                    menuSheet.Cells[i + 2, 1].Style.Font.Color.SetColor(System.Drawing.Color.Blue); // 设置为蓝色文本  
                }

                // 保存Excel文件  
                string date = DateTime.Now.ToString().Replace('/', '_').Replace(':', '_');
                FileInfo excelFile = new FileInfo($"{this.TestVisibleLineComboBox.Text}试卷_{date}导出.xlsx");
                package.SaveAs(excelFile);
                MessageBox.Show($"导出成功:{this.TestVisibleLineComboBox.Text}试卷_{date}导出.xlsx");
            }
        }

        #endregion

        #region 按线路导出学员试卷 北京运二
        private void SaveExcelFileByLineStudent()
        {
            using (ExcelPackage package = new ExcelPackage())
            {
                List<postModel> roleModels = PostDAL.GetPostInfo();
                ExcelWorksheet menuSheet = package.Workbook.Worksheets.Add("目录");

                ObservableCollection<TestQuestionViewModel> papers = this.ShowQuestionList;
                menuSheet.Cells[1, 1].Value = "场景名称";
                menuSheet.Column(1).Width = 50;
                menuSheet.Cells[1, 1].Style.Font.Size = 20;
                menuSheet.Cells[1, 1].Style.Font.Bold = true;
                menuSheet.Cells[1, 2].Value = "包含岗位";
                menuSheet.Column(2).Width = 80;
                menuSheet.Cells[1, 2].Style.Font.Size = 20;
                menuSheet.Cells[1, 2].Style.Font.Bold = true;




                foreach (var selectedTestQuestion in ShowQuestionList)
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(selectedTestQuestion.TestName);

                    List<Paper_TestQuestion_TaskModel> taskList = Paper_TestQuestion_TaskDAL.GetMyPaper_TestQuestion_TaskModel(selectedTestQuestion.Id);
                    worksheet.Cells[1, 1].Value = selectedTestQuestion.TestName;
                    worksheet.Cells[$"A1:G1"].Merge = true;
                    worksheet.Row(1).Height = 50;
                    worksheet.Cells[1, 1].Style.Font.Size = 36;
                    worksheet.Cells[1, 1].Style.Font.Bold = true;
                    worksheet.Cells[1, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    string targetSheetName = "目录"; // 或者根据你的逻辑来设置sheet名

                    // 使用HYPERLINK函数设置超链接  
                    string hyperlinkFormula = $"=HYPERLINK(\"#'{targetSheetName}'!A1\", \"{selectedTestQuestion.TestName}\")";
                    worksheet.Cells[1, 1].Formula = hyperlinkFormula;
                    worksheet.Cells[1, 1].Style.Font.UnderLine = true;
                    worksheet.Cells[1, 1].Style.Font.Color.SetColor(System.Drawing.Color.Blue); // 设置为蓝色文本  

                    worksheet.Cells[2, 1].Value = selectedTestQuestion.Describes;
                    worksheet.Cells[$"A2:G2"].Merge = true;
                    worksheet.Row(2).Height = 50;
                    worksheet.Row(2).Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                    worksheet.Row(2).Style.WrapText = true;
                    worksheet.Cells[2, 1].Style.Font.Size = 12;
                    worksheet.Cells[2, 1].Style.Font.Bold = true;
                    worksheet.Cells[2, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    for (int j = 1; j <= 7; j++)
                    {
                        worksheet.Column(j).Width = 20;
                        worksheet.Cells[3, j].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        worksheet.Cells[3, j].Style.Font.Size = 16;
                        worksheet.Cells[3, j].Style.Font.Bold = true;
                    }
                    worksheet.Column(3).Width = 30;
                    worksheet.Column(6).Width = 50;

                    worksheet.Cells[3, 1].Value = "作业程序";
                    worksheet.Cells[3, 2].Value = "步骤类型";
                    worksheet.Cells[3, 3].Value = "操作类型";
                    worksheet.Cells[3, 4].Value = "设备类型";
                    worksheet.Cells[3, 5].Value = "设备";
                    worksheet.Cells[3, 6].Value = "步骤内容";
                    worksheet.Cells[3, 7].Value = "关键词";

                    int i = 4;
                    int k = 0;
                    foreach (Paper_TestQuestion_TaskModel task in taskList)
                    {
                        k++;

                        task.TestQuestionTaskSteps = Paper_TestQuestion_Task_StepDAL.GetMyPaper_TestQuestion_Task_StepModel(task.Id);
                        if (task.TestQuestionTaskSteps.Count < 1)
                        {
                            continue;
                        }
                        worksheet.Cells[i, 1].Value = task.Describes;
                        worksheet.Cells[$"A{i}:A{i + task.TestQuestionTaskSteps.Count - 1}"].Merge = true;
                        ExcelRange range = worksheet.Cells[$"A{i}:G{i + task.TestQuestionTaskSteps.Count - 1}"];
                        range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                        if (k % 2 == 0)
                        {
                            range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                        }
                        else
                        {
                            range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.White);

                        }

                        foreach (var step in task.TestQuestionTaskSteps.OrderBy(x => x.UIOrder))
                        {
                            ConvertToExcelByLineStudent(worksheet, step, i);
                            i++;
                        }
                    }

                    ExcelRange allRange = worksheet.Cells[$"A1:G{i}"];
                    allRange.Style.Border.Top.Style = ExcelBorderStyle.Thin; // 上边框  
                    allRange.Style.Border.Bottom.Style = ExcelBorderStyle.Thin; // 下边框  
                    allRange.Style.Border.Left.Style = ExcelBorderStyle.Thin; // 左边框  
                    allRange.Style.Border.Right.Style = ExcelBorderStyle.Thin; // 右边框  
                }


                //目录超链接
                for (int i = 0; i < papers.Count; i++)
                {
                    if (!string.IsNullOrEmpty(papers[i].TestName))
                    {
                        menuSheet.Cells[i + 2, 1].Value = papers[i].TestName;
                    }
                    if (!string.IsNullOrEmpty(papers[i].Roles))
                    {
                        menuSheet.Cells[i + 2, 2].Value = string.Join(",", papers[i].Roles.Split(',').ToList().Select(x => roleModels.FirstOrDefault(t => t.post_id == x).post_name));

                    }
                    string targetSheetName = papers[i].TestName; // 或者根据你的逻辑来设置sheet名  

                    // 使用HYPERLINK函数设置超链接  
                    string hyperlinkFormula = $"=HYPERLINK(\"#'{targetSheetName}'!A1\", \"{papers[i].TestName}\")";
                    menuSheet.Cells[i + 2, 1].Formula = hyperlinkFormula;
                    menuSheet.Cells[i + 2, 1].Style.Font.UnderLine = true;
                    menuSheet.Cells[i + 2, 1].Style.Font.Color.SetColor(System.Drawing.Color.Blue); // 设置为蓝色文本  
                }

                // 保存Excel文件  
                string date = DateTime.Now.ToString().Replace('/', '_').Replace(':', '_');
                FileInfo excelFile = new FileInfo($"{this.TestVisibleLineComboBox.Text}试卷_{date}导出.xlsx");
                package.SaveAs(excelFile);
                MessageBox.Show($"导出成功:{this.TestVisibleLineComboBox.Text}试卷_{date}导出.xlsx");
            }
        }
        #endregion

        #region 导出
        private void SaveExcelFile()
        {
            using (ExcelPackage package = new ExcelPackage())
            {
                List<postModel> roleModels = PostDAL.GetPostInfo();
                ExcelWorksheet menuSheet = package.Workbook.Worksheets.Add("目录");

                ObservableCollection<TestQuestionViewModel> papers = this.QuestionList;
                menuSheet.Cells[1, 1].Value = "场景名称";
                menuSheet.Column(1).Width = 50;
                menuSheet.Cells[1, 1].Style.Font.Size = 20;
                menuSheet.Cells[1, 1].Style.Font.Bold = true;
                menuSheet.Cells[1, 2].Value = "包含岗位";
                menuSheet.Column(2).Width = 80;
                menuSheet.Cells[1, 2].Style.Font.Size = 20;
                menuSheet.Cells[1, 2].Style.Font.Bold = true;




                foreach (var selectedTestQuestion in QuestionList)
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(selectedTestQuestion.TestName);

                    List<Paper_TestQuestion_TaskModel> taskList = Paper_TestQuestion_TaskDAL.GetMyPaper_TestQuestion_TaskModel(selectedTestQuestion.Id);
                    worksheet.Cells[1, 1].Value = selectedTestQuestion.TestName;
                    worksheet.Cells[$"A1:O1"].Merge = true;
                    worksheet.Row(1).Height = 50;
                    worksheet.Cells[1, 1].Style.Font.Size = 36;
                    worksheet.Cells[1, 1].Style.Font.Bold = true;
                    worksheet.Cells[1, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    string targetSheetName = "目录"; // 或者根据你的逻辑来设置sheet名

                    // 使用HYPERLINK函数设置超链接  
                    string hyperlinkFormula = $"=HYPERLINK(\"#'{targetSheetName}'!A1\", \"{selectedTestQuestion.TestName}\")";
                    worksheet.Cells[1, 1].Formula = hyperlinkFormula;
                    worksheet.Cells[1, 1].Style.Font.UnderLine = true;
                    worksheet.Cells[1, 1].Style.Font.Color.SetColor(System.Drawing.Color.Blue); // 设置为蓝色文本  

                    worksheet.Cells[2, 1].Value = selectedTestQuestion.Describes;
                    worksheet.Cells[$"A2:O2"].Merge = true;
                    worksheet.Row(2).Height = 30;
                    worksheet.Cells[2, 1].Style.Font.Size = 12;
                    worksheet.Cells[2, 1].Style.Font.Bold = true;
                    worksheet.Cells[2, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    for (int j = 1; j <= 15; j++)
                    {
                        worksheet.Column(j).Width = 20;
                        worksheet.Cells[3, j].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        worksheet.Cells[3, j].Style.Font.Size = 16;
                        worksheet.Cells[3, j].Style.Font.Bold = true;
                    }
                    worksheet.Column(5).Width = 30;
                    worksheet.Column(8).Width = 50;
                    worksheet.Column(15).Width = 50;

                    worksheet.Cells[3, 1].Value = "作业程序";
                    worksheet.Cells[3, 2].Value = "所属系统";
                    worksheet.Cells[3, 3].Value = "岗位";
                    worksheet.Cells[3, 4].Value = "步骤类型";
                    worksheet.Cells[3, 5].Value = "操作类型";
                    worksheet.Cells[3, 6].Value = "设备类型";
                    worksheet.Cells[3, 7].Value = "设备";
                    worksheet.Cells[3, 8].Value = "步骤内容";
                    worksheet.Cells[3, 9].Value = "参数";
                    worksheet.Cells[3, 10].Value = "关键词";
                    worksheet.Cells[3, 11].Value = "前置状态";
                    worksheet.Cells[3, 12].Value = "配分";
                    worksheet.Cells[3, 13].Value = "前提条件";
                    worksheet.Cells[3, 14].Value = "UIOrder";
                    worksheet.Cells[3, 15].Value = "是否为持续性判断";
                    int i = 4;
                    int k = 0;
                    foreach (Paper_TestQuestion_TaskModel task in taskList)
                    {
                        k++;

                        task.TestQuestionTaskSteps = Paper_TestQuestion_Task_StepDAL.GetMyPaper_TestQuestion_Task_StepModel(task.Id);
                        if (task.TestQuestionTaskSteps.Count < 1)
                        {
                            continue;
                        }
                        worksheet.Cells[i, 1].Value = task.Describes;
                        worksheet.Cells[$"A{i}:A{i + task.TestQuestionTaskSteps.Count - 1}"].Merge = true;
                        ExcelRange range = worksheet.Cells[$"A{i}:O{i + task.TestQuestionTaskSteps.Count - 1}"];
                        range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                        if (k % 2 == 0)
                        {
                            range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                        }
                        else
                        {
                            range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.White);

                        }

                        foreach (var step in task.TestQuestionTaskSteps.OrderBy(x => x.UIOrder))
                        {
                            ConvertToExcel(worksheet, step, i);
                            i++;
                        }
                    }

                    ExcelRange allRange = worksheet.Cells[$"A1:O{i}"];
                    allRange.Style.Border.Top.Style = ExcelBorderStyle.Thin; // 上边框  
                    allRange.Style.Border.Bottom.Style = ExcelBorderStyle.Thin; // 下边框  
                    allRange.Style.Border.Left.Style = ExcelBorderStyle.Thin; // 左边框  
                    allRange.Style.Border.Right.Style = ExcelBorderStyle.Thin; // 右边框  
                }


                //目录超链接
                for (int i = 0; i < papers.Count; i++)
                {
                    if (!string.IsNullOrEmpty(papers[i].TestName))
                    {
                        menuSheet.Cells[i + 2, 1].Value = papers[i].TestName;
                    }
                    if (!string.IsNullOrEmpty(papers[i].Roles))
                    {
                        menuSheet.Cells[i + 2, 2].Value = string.Join(",", papers[i].Roles.Split(',').ToList().Select(x => roleModels.FirstOrDefault(t => t.post_id == x).post_name));

                    }
                    string targetSheetName = papers[i].TestName; // 或者根据你的逻辑来设置sheet名  

                    // 使用HYPERLINK函数设置超链接  
                    string hyperlinkFormula = $"=HYPERLINK(\"#'{targetSheetName}'!A1\", \"{papers[i].TestName}\")";
                    menuSheet.Cells[i + 2, 1].Formula = hyperlinkFormula;
                    menuSheet.Cells[i + 2, 1].Style.Font.UnderLine = true;
                    menuSheet.Cells[i + 2, 1].Style.Font.Color.SetColor(System.Drawing.Color.Blue); // 设置为蓝色文本  
                }

                // 保存Excel文件  
                string date = DateTime.Now.ToString().Replace('/', '_').Replace(':', '_');
                FileInfo excelFile = new FileInfo($"全部试卷_{date}导出.xlsx");
                package.SaveAs(excelFile);
                MessageBox.Show($"导出成功:全部试卷_{date}导出.xlsx");
            }
        }

        private void SaveExcelFile(TestQuestionViewModel selectedTestQuestion)
        {
            //ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            using (ExcelPackage package = new ExcelPackage())
            {
                // 添加一个工作表  
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(selectedTestQuestion.TestName);

                List<Paper_TestQuestion_TaskModel> taskList = Paper_TestQuestion_TaskDAL.GetMyPaper_TestQuestion_TaskModel(selectedTestQuestion.Id);
                worksheet.Cells[1, 1].Value = SelectedTestQuestion.TestName;
                worksheet.Cells[$"A1:O1"].Merge = true;
                worksheet.Row(1).Height = 50;
                worksheet.Cells[1, 1].Style.Font.Size = 36;
                worksheet.Cells[1, 1].Style.Font.Bold = true;
                worksheet.Cells[1, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;


                worksheet.Cells[2, 1].Value = selectedTestQuestion.Describes;
                worksheet.Cells[$"A2:O2"].Merge = true;
                worksheet.Row(2).Height = 30;
                worksheet.Cells[2, 1].Style.Font.Size = 12;
                worksheet.Cells[2, 1].Style.Font.Bold = true;
                worksheet.Cells[2, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                for (int j = 1; j <= 15; j++)
                {
                    worksheet.Column(j).Width = 20;
                    worksheet.Cells[3, j].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    worksheet.Cells[3, j].Style.Font.Size = 16;
                    worksheet.Cells[3, j].Style.Font.Bold = true;

                }
                worksheet.Column(5).Width = 30;
                worksheet.Column(8).Width = 50;
                worksheet.Column(15).Width = 50;

                worksheet.Cells[3, 1].Value = "作业程序";
                worksheet.Cells[3, 2].Value = "所属系统";
                worksheet.Cells[3, 3].Value = "岗位";
                worksheet.Cells[3, 4].Value = "步骤类型";
                worksheet.Cells[3, 5].Value = "操作类型";
                worksheet.Cells[3, 6].Value = "设备类型";
                worksheet.Cells[3, 7].Value = "设备";
                worksheet.Cells[3, 8].Value = "步骤内容";
                worksheet.Cells[3, 9].Value = "参数";
                worksheet.Cells[3, 10].Value = "关键词";
                worksheet.Cells[3, 11].Value = "前置状态";
                worksheet.Cells[3, 12].Value = "配分";
                worksheet.Cells[3, 13].Value = "前提条件";
                worksheet.Cells[3, 14].Value = "UIOrder";
                worksheet.Cells[3, 15].Value = "是否为持续性判断";
                int i = 4;
                int k = 0;
                foreach (var task in taskList)
                {
                    k++;
                    task.TestQuestionTaskSteps = Paper_TestQuestion_Task_StepDAL.GetMyPaper_TestQuestion_Task_StepModel(task.Id);
                    worksheet.Cells[i, 1].Value = task.Describes;
                    worksheet.Cells[$"A{i}:A{i + task.TestQuestionTaskSteps.Count - 1}"].Merge = true;
                    ExcelRange range = worksheet.Cells[$"A{i}:O{i + task.TestQuestionTaskSteps.Count - 1}"];
                    range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    if (k % 2 == 0)
                    {
                        range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
                    }
                    else
                    {
                        range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.White);

                    }

                    foreach (var step in task.TestQuestionTaskSteps.OrderBy(x => x.UIOrder))
                    {
                        ConvertToExcel(worksheet, step, i);
                        i++;
                    }
                }

                ExcelRange allRange = worksheet.Cells[$"A1:O{i}"];
                allRange.Style.Border.Top.Style = ExcelBorderStyle.Thin; // 上边框  
                allRange.Style.Border.Bottom.Style = ExcelBorderStyle.Thin; // 下边框  
                allRange.Style.Border.Left.Style = ExcelBorderStyle.Thin; // 左边框  
                allRange.Style.Border.Right.Style = ExcelBorderStyle.Thin; // 右边框  

                // 保存Excel文件  
                string date = DateTime.Now.ToString().Replace('/', '_').Replace(':', '_');
                FileInfo excelFile = new FileInfo($"{selectedTestQuestion.TestName}_{date}导出.xlsx");
                package.SaveAs(excelFile);
                MessageBox.Show($"导出成功,{excelFile.Name}导出.xlsx");
            }
        }

        private void ConvertToExcel(ExcelWorksheet worksheet, Paper_TestQuestion_Task_StepModel step, int index)
        {
            for (int i = 1; i <= 15; i++)
            {
                worksheet.Cells[index, i].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                worksheet.Cells[index, i].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
            }
            //所属系统
            worksheet.Cells[index, 2].Value = step.SysType;
            //岗位
            worksheet.Cells[index, 3].Value = GetPostNames(step.RoleId);
            //步骤类型
            worksheet.Cells[index, 4].Value = step.TaskType;
            //操作类型
            worksheet.Cells[index, 5].Value = GetOperationName(step.OperateId);
            //设备类型
            worksheet.Cells[index, 6].Value = GetdeviceTypeName(step.DevicetypeId);
            //设备
            worksheet.Cells[index, 7].Value = GetDeviceNameByLine(step.DeviceId, step.DevicetypeId, GetLineNameEnum(this.TestVisibleLineComboBox.Text).ToString());
            //步骤内容
            worksheet.Cells[index, 8].Value = step.Describes;
            worksheet.Cells[index, 8].Style.WrapText = true;
            //参数
            worksheet.Cells[index, 9].Value = step.Parameter;
            //关键词
            worksheet.Cells[index, 10].Value = step.KeyWords;
            //配分
            worksheet.Cells[index, 12].Value = step.Score;
            //前提条件
            worksheet.Cells[index, 13].Value = step.Prerequisite;
            //UIOrder
            worksheet.Cells[index, 14].Value = step.UIOrder;
            //持续性判断
            worksheet.Cells[index, 15].Value = GetIsContinued(step.IsContinued, step.TaskType);
        }

        private void ConvertToExcelByLineStudent(ExcelWorksheet worksheet, Paper_TestQuestion_Task_StepModel step, int index)
        {
            for (int i = 1; i <= 7; i++)
            {
                worksheet.Cells[index, i].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                worksheet.Cells[index, i].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
            }
            //步骤类型
            worksheet.Cells[index, 2].Value = step.TaskType;
            //操作类型
            worksheet.Cells[index, 3].Value = GetOperationName(step.OperateId);
            //设备类型
            worksheet.Cells[index, 4].Value = GetdeviceTypeName(step.DevicetypeId);
            //设备
            worksheet.Cells[index, 5].Value = GetDeviceNameByLine(step.DeviceId, step.DevicetypeId, GetLineNameEnum(this.TestVisibleLineComboBox.Text).ToString());
            //步骤内容
            worksheet.Cells[index, 6].Value = step.Describes;
            worksheet.Cells[index, 6].Style.WrapText = true;
            //关键词
            worksheet.Cells[index, 7].Value = step.KeyWords;
        }


        private static string GetOperationName(int operationId)
        {
            var operation = OperateItemModels.FirstOrDefault(x => x.Id == operationId);
            if (operation != null)
            {
                return operation.Describes;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 导出时检查是否为可持续性判断步骤
        /// </summary>
        /// <param name="isContinued">“1”为是持续性判断 其他不是</param>
        /// <param name="taskType">taskType为仿真</param>
        /// <returns></returns>
        private string GetIsContinued(string isContinued, string taskType)
        {
            if (isContinued == "1" && taskType == "仿真") return "是";
            return string.Empty;
        }
        private static string GetIsContinued(dynamic isContinued)
        {

            if (isContinued == "是" || isContinued == "true")
            {
                return "1";
            }
            return string.Empty;
        }
        private string GetDeviceName(string deviceId, int deviceTypeId)
        {
            List<string> devices = deviceId.Split(',').ToList();
            List<string> deviceNames = new List<string>();
            foreach (string device in devices)
            {
                var deviceModel = DeviceModels.FirstOrDefault(x => x.DeviceId.ToString() == device && x.DeviceTypeId == deviceTypeId);
                if (deviceModel != null)
                {
                    deviceNames.Add(deviceModel.DeviceName);
                }
            }
            return string.Join(",", deviceNames);
        }
        /// <summary>
        /// 根据线路筛选设备名称
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="deviceTypeId"></param>
        /// <param name="line"></param>
        /// <returns></returns>
        private string GetDeviceNameByLine(string deviceId, int deviceTypeId, string line)
        {
            List<string> devices = deviceId.Split(',').ToList();
            List<string> deviceNames = new List<string>();
            foreach (string device in devices)
            {
                var deviceModel = DeviceModels.FirstOrDefault(x => x.DeviceId.ToString() == device && x.DeviceTypeId == deviceTypeId && (x.LineName == line || x.LineName == "None"));
                if (deviceModel != null)
                {
                    deviceNames.Add(deviceModel.DeviceName);
                }
            }
            return string.Join(",", deviceNames);
        }

        private string GetdeviceTypeName(int deviceTypeId)
        {
            var devicetypeModel = DeviceTypeModels.FirstOrDefault(x => x.Id == deviceTypeId);
            if (devicetypeModel != null)
            {
                return devicetypeModel.DeviceType;
            }
            else
            {
                return "";
            }
        }

        public string GetPostNames(string RoleId)
        {
            if (RoleId == null)
            {
                return "";
            }
            List<string> roleIdList = RoleId.Split(',').ToList();
            List<string> roleNames = new List<string>();
            foreach (string roleId in roleIdList)
            {
                var post = PostModels.FirstOrDefault(x => x.post_id == roleId);
                if (post != null)
                {
                    roleNames.Add(post.post_name);
                }

            }
            return string.Join(",", roleNames);
        }
        #endregion


        #region 导入功能
        public void ReadExcelFile(string filePath, int questionId = 0)
        {
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filePath);

            // 获取所有工作表的名称  
            int sheetCount = xlWorkbook.Sheets.Count;
            List<string> sheetNames = new List<string>();

            for (int i = 1; i <= sheetCount; i++)
            {
                Excel._Worksheet sheet = (Excel._Worksheet)xlWorkbook.Sheets[i];
                sheetNames.Add(sheet.Name);
                // 如果你不需要进一步操作sheet对象，可以立即释放它  
                Marshal.ReleaseComObject(sheet);
            }

            ChooseExcelSheet chooseExcelSheet = new ChooseExcelSheet(sheetNames);
            string selectedSheetName = string.Empty;
            if (chooseExcelSheet.ShowDialog() == false)
            {
                return;
            }
            else
            {
                selectedSheetName = chooseExcelSheet.cbSheetName.SelectedItem.ToString();
            }

            Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[selectedSheetName];
            Excel.Range xlRange = xlWorksheet.UsedRange;
            var a = xlRange.Cells[3, 2].value.ToString();
            //如果模板不对则返回并报错 add by peizhankun
            if (xlRange.Cells[3, 2].value.ToString() != "所属系统")
            {
                MessageBox.Show("请检查所使用模板！！");
                return;
            }

            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;
            var paperModel = GetPaperModel(xlRange);
            //Enum.TryParse(GetLineNameEnum(this.TestVisibleLineComboBox.Text).ToString(), out LineNameEnum line);
            //if (!paperModel.TestName.Contains(GetLineNameAttribute(line)) && this.TestVisibleLineComboBox.Text != "全部")
            //如果发现试卷中带有线路名称即不再拼接线路名称
            if (GetAddNameFlag(Enum.GetValues(typeof(LineNameEnum)), paperModel.TestName))
            {
                if (this.TestVisibleLineComboBox.Text != "全部" && !paperModel.TestName.Contains(this.TestVisibleLineComboBox.Text))
                    paperModel.TestName += $" - {this.TestVisibleLineComboBox.Text}";
            }
            else
            {
                MessageBox.Show("导入失败");
                return;
            }
            if (paperModel != null)
            {
                if (questionId == 0)
                {
                    ET_DbCommon.DAL.Paper_TestQuestionDAL.Insert(paperModel, out int newID);
                    var paperTaskModels = GetPaperTaskModels(xlRange, newID);
                    ET_DbCommon.DAL.Paper_TestQuestion_TaskDAL.Insert(paperTaskModels);
                    var paperTaskStepModels = GetPaperTaskStepModels(xlRange, newID);
                    ET_DbCommon.DAL.Paper_TestQuestion_Task_StepDAL.Insert(paperTaskStepModels);
                }
                else
                {
                    var tasks = ET_DbCommon.DAL.Paper_TestQuestion_TaskDAL.GetMyPaper_TestQuestion_TaskModel(questionId);
                    foreach (var task in tasks)
                    {
                        ET_DbCommon.DAL.Paper_TestQuestion_TaskDAL.DeleteByID(task.Id);
                    }
                    var paperTaskModels = GetPaperTaskModels(xlRange, questionId);
                    ET_DbCommon.DAL.Paper_TestQuestion_TaskDAL.Insert(paperTaskModels);
                    var paperTaskStepModels = GetPaperTaskStepModels(xlRange, questionId);
                    ET_DbCommon.DAL.Paper_TestQuestion_Task_StepDAL.Insert(paperTaskStepModels);
                }

            }


            xlWorkbook.Close();
            xlApp.Quit();
            MessageBox.Show("导入完成");
        }
        /// <summary>
        /// 判断是否含有线路名称
        /// </summary>
        /// <param name="array">线路枚举</param>
        /// <param name="paperName">名称</param>
        /// <returns></returns>
        private bool GetAddNameFlag(Array array, string paperName)
        {
            foreach (var item in array)
            {
                if (paperName.Contains(GetLineNameAttribute((LineNameEnum)item)))
                {
                    if (this.TestVisibleLineComboBox.Text != GetLineNameAttribute((LineNameEnum)item))
                    {
                        MessageBox.Show($"请检查场景文件标题与所选线路一致! \n当前软件所选线路为：{this.TestVisibleLineComboBox.Text}！\n场景所选线路为：{GetLineNameAttribute((LineNameEnum)item)}！");
                        return false;
                    }

                }
            }
            return true;
        }

        /// <summary>
        /// 获取Paper信息
        /// </summary>
        /// <param name="xlRange"></param>
        /// <returns></returns>
        private static ET_DbCommon.Model.Paper_TestQuestionModel GetPaperModel(Excel.Range xlRange)
        {


            int rowCount = xlRange.Rows.Count;

            //场景名称
            string paperName = string.Empty;
            if (xlRange.Cells[1, 1].Value != null)
            {

                paperName = xlRange.Cells[1, 1].Value;

            }

            //场景描述
            string paperDescribes = string.Empty;
            if (xlRange.Cells[2, 1].Value != null)
            {
                paperDescribes = xlRange.Cells[2, 1].Value;
            }

            //场景包含岗位
            List<string> postName = new List<string>();
            //var postList = ET_DbCommon.DAL.PostDAL.GetPostInfo();
            for (int i = 4; i < rowCount; i++)
            {
                string post_Id = GetRoleID(xlRange.Cells[i, 3].Value);

                if (!postName.Contains(post_Id) && post_Id != "")
                {
                    postName.Add(post_Id);
                }
            }
            string Roles = string.Join(",", postName);


            ET_DbCommon.Model.Paper_TestQuestionModel paperModel = new ET_DbCommon.Model.Paper_TestQuestionModel()
            {
                TestName = paperName,
                CountDown = 2400,
                Describes = paperDescribes,
                SceneFile = 0,
                IsMain = "True",
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                Roles = Roles,
            };

            return paperModel;
        }

        private static List<ET_DbCommon.Model.Paper_TestQuestion_TaskModel> GetPaperTaskModels(Excel.Range xlRange, int paperID)
        {
            int rowCount = xlRange.Rows.Count;
            List<string> taskNames = new List<string>();

            for (int i = 4; i < rowCount; i++)
            {
                var val = xlRange.Cells[i, 1].Value;
                if (val != null)
                {
                    //if (!taskNames.Contains(val))
                    //{
                    taskNames.Add(val);
                    //}
                }
            }
            List<ET_DbCommon.Model.Paper_TestQuestion_TaskModel> taskModels = new List<ET_DbCommon.Model.Paper_TestQuestion_TaskModel>();
            for (int i = 0; i < taskNames.Count; i++)
            {

                ET_DbCommon.Model.Paper_TestQuestion_TaskModel taskModel = new ET_DbCommon.Model.Paper_TestQuestion_TaskModel()
                {
                    TestId = paperID,
                    Describes = /*$"{(i + 1).ToString()}、" +*/ taskNames[i],
                    Order = i + 1,
                    UiOrder = i + 1,
                    TaskType = "任务",
                    IsMain = true,
                };
                if (taskNames[i].Contains("非主线"))
                {
                    taskModel.IsMain = false;
                }


                taskModels.Add(taskModel);
            }
            return taskModels;
        }
        public static List<ET_DbCommon.Model.OperateItemModel> OperateItemModels = new List<ET_DbCommon.Model.OperateItemModel>();
        public static List<ET_DbCommon.Model.Device_TypeModel> DeviceTypeModels = new List<ET_DbCommon.Model.Device_TypeModel>();
        public static List<ET_DbCommon.Model.DeviceModel> DeviceModels = new List<ET_DbCommon.Model.DeviceModel>();
        public static List<ET_DbCommon.Model.postModel> PostModels = new List<ET_DbCommon.Model.postModel>();

        private static List<ET_DbCommon.Model.Paper_TestQuestion_Task_StepModel> GetPaperTaskStepModels(Excel.Range xlRange, int paperID)
        {
            List<ET_DbCommon.Model.Paper_TestQuestion_Task_StepModel> stepModels = new List<ET_DbCommon.Model.Paper_TestQuestion_Task_StepModel>();
            int rowCount = xlRange.Rows.Count;
            var operations = ET_DbCommon.DAL.OperateItemDAL.GetOperateItems();
            var taskModels = ET_DbCommon.DAL.Paper_TestQuestion_TaskDAL.GetMyPaper_TestQuestion_TaskModel(paperID);
            ET_DbCommon.Model.Paper_TestQuestion_TaskModel currentTask = new ET_DbCommon.Model.Paper_TestQuestion_TaskModel();
            int UIOrderID = 1;
            int taskOrderID = 1;
            for (int i = 4; i < rowCount; i++)
            {
                var taskName = xlRange.Cells[i, 1].Value;
                if (taskName != null)
                {
                    //taskName = $"{(taskOrderID).ToString()}、" + taskName;
                    currentTask = taskModels.FirstOrDefault(x => x.Describes == taskName);
                    UIOrderID = 1;
                    taskOrderID++;
                }
                ET_DbCommon.Model.Paper_TestQuestion_Task_StepModel stepModel = new ET_DbCommon.Model.Paper_TestQuestion_Task_StepModel();



                stepModel.TaskId = currentTask.Id;
                stepModel.OperateId = GetOperateID(xlRange.Cells[i, 5].Value);
                stepModel.Parameter = GetParameter(xlRange.Cells[i, 9].Value);
                stepModel.Score = GetScore(xlRange.Cells[i, 12].Value);
                stepModel.SysType = xlRange.Cells[i, 2].Value;
                stepModel.TaskType = xlRange.Cells[i, 4].Value;
                stepModel.Describes = xlRange.Cells[i, 8].Value;
                stepModel.DevicetypeId = GetDeviceTypeID(xlRange.Cells[i, 6].Value);
                stepModel.DeviceId = GetDeviceID(xlRange.Cells[i, 7].Value, xlRange.Cells[i, 6].Value);
                if (stepModel.SysType == "VR" && stepModel.OperateId == 95)
                {//VR且无线电台呼入 => 直接返回Describes;
                    stepModel.StepContent = stepModel.Describes;
                }
                else
                {
                    stepModel.StepContent = GetStepContent(xlRange.Cells[i, 8].Value);
                }
                stepModel.Prerequisite = "";
                stepModel.KeyWords = GetKeyWords(xlRange.Cells[i, 10].Value);
                stepModel.RoleId = GetRoleID(xlRange.Cells[i, 3].Value);
                stepModel.UIOrder = GetUIOrder(xlRange.Cells[i, 14].Value, UIOrderID);
                stepModel.IsContinued = GetIsContinued(xlRange.Cells[i, 15].Value);
                if (xlRange.Cells[3, 13].Value == "前提条件")
                {
                    stepModel.Prerequisite = GetPrerequisite(xlRange.Cells[i, 13].Value);
                }
                if (GetRemark(xlRange.Cells[i, 11].value) != string.Empty)
                {
                    MessageBox.Show($"第{taskOrderID - 1}个任务的第{stepModel.UIOrder}个步骤有个备注{xlRange.Cells[i, 11].value}，请查看！！");
                }

                UIOrderID++;
                if (!JudgeKeyWordInContent(stepModel.StepContent, stepModel.KeyWords))
                {
                    MessageBox.Show($"Excel第{i}行, 任务内容：{stepModel.StepContent}中不包含关键词:{stepModel.KeyWords}");
                }

                //List<int> CallOutIDS = new List<int>() { 92, 96, 140, 141, 240 ,256,257};
                //if (!CallOutIDS.Contains(stepModel.OperateId))
                //{
                //    if (stepModel.KeyWords != null && stepModel.KeyWords != "")
                //    {
                //        MessageBox.Show($"非呼出步骤：{stepModel.StepContent}中存在关键词${stepModel.KeyWords}");
                //    }
                //}

                if (!string.IsNullOrEmpty(stepModel.SysType))
                {
                    stepModels.Add(stepModel);
                }
                else
                {
                    //MessageBox.Show($"Excel第{i}行，缺少步骤内容");
                }

            }
            return stepModels;
        }
        private static int GetUIOrder(dynamic order, int currentOrder)
        {
            if (order == null)
            {
                return currentOrder;
            }
            else
            {
                if (int.TryParse(order.ToString(), out int orderID))
                {
                    return orderID;
                }
            }
            return currentOrder;
        }
        private static string GetKeyWords(dynamic keywordDyn)
        {
            if (keywordDyn == null)
            {
                return "";
            }
            return keywordDyn.ToString();
        }
        private static string GetRemark(dynamic Remark)
        {
            if (Remark == null)
            {
                return "";
            }
            return Remark.ToString();
        }
        private static string GetPrerequisite(dynamic prerequisite)
        {
            if (string.IsNullOrEmpty(prerequisite))
            {
                return string.Empty;
            }
            else
            {
                return prerequisite.ToString();
            }

        }

        private static bool JudgeKeyWordInContent(string stepContent, string keyWords)
        {
            if (string.IsNullOrEmpty(stepContent) || string.IsNullOrEmpty(keyWords))
            {
                return true;
            }
            List<string> keyWordList = keyWords.Split('、').ToList();
            foreach (var keyWord in keyWordList)
            {
                List<string> OrKeyWords = keyWord.Split('|').ToList();
                if (!OrKeyWords.Any(x => stepContent.Contains(x)))
                {
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 获取参数
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static string GetParameter(dynamic value)
        {
            if (value == null)
            {
                return string.Empty;
            }
            else
            {
                return value.ToString();
            }
        }

        private static decimal GetScore(dynamic score)
        {
            if (score == null)
            {
                return 0;
            }
            else
            {
                return (decimal)score;
            }
        }

        private static string GetStepContent(dynamic describes)
        {
            if (describes == null) { return string.Empty; }
            string describesString = describes.ToString();
            describesString = describesString.Replace('“', '"').Replace('”', '"');
            int startIndex = describesString.IndexOf('"') + 1; // 找到第一个引号后的位置  
            int endIndex = describesString.LastIndexOf('"'); // 找到最后一个引号的位置  
            if (startIndex < endIndex)
            {
                string content = describesString.Substring(startIndex, endIndex - startIndex); // 提取引号中的内容  
                return content;
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取岗位ID
        /// </summary>
        /// <param name="postName"></param>
        /// <returns></returns>
        private static string GetRoleID(dynamic postName)
        {
            string postNamesString = postName as string;
            if (string.IsNullOrEmpty(postNamesString))
            {
                return "";
            }
            List<string> postNamesList = postNamesString.Split(',').ToList();
            List<string> postIds = new List<string>();
            foreach (string name in postNamesList)
            {
                var model = PostModels.FirstOrDefault(x => x.post_name == name);
                if (model != null)
                {
                    postIds.Add(model.post_id);
                    //return model.post_id;
                }
                else
                {
                    MessageBox.Show($"获取岗位ID错误, 无法找到{postName}的岗位ID");
                    return "";
                }
            }
            return string.Join(",", postIds);

        }

        /// <summary>
        /// 获取设备ID
        /// </summary>
        /// <param name="deviceNames"></param>
        /// <param name="deviceTypeName"></param>
        /// <returns></returns>
        private static string GetDeviceID(dynamic deviceNames, dynamic deviceTypeName)
        {
            if (deviceNames == null || deviceTypeName == null) { return string.Empty; }
            var deviceTypeID = GetDeviceTypeID(deviceTypeName);
            var devcieNameStr = deviceNames.ToString();
            var deviceNamesStr = devcieNameStr as string;
            List<string> deviceNameList = deviceNamesStr.Split(',').ToList();
            List<int> deviceIds = new List<int>();
            foreach (var deviceName in deviceNameList)
            {
                var model = DeviceModels.FirstOrDefault(x => x.DeviceTypeId == deviceTypeID && x.DeviceName == deviceName);
                if (model != null)
                {
                    deviceIds.Add(model.DeviceId);
                }
                else
                {
                    MessageBox.Show(messageBoxText: $"获取设备ID错误, 无法找到名称:{deviceName}, 设备类型:{deviceTypeName}");
                    return "";
                }
            }
            return string.Join(",", deviceIds);
        }

        /// <summary>
        /// 获取设备类型ID
        /// </summary>
        /// <param name="deviceType"></param>
        /// <returns></returns>
        private static int GetDeviceTypeID(dynamic deviceType)
        {
            if (deviceType == null) { return 0; }
            var model = DeviceTypeModels.FirstOrDefault(x => x.DeviceType == deviceType);
            if (model != null)
            {
                return model.Id;
            }
            else
            {
                MessageBox.Show(messageBoxText: $"获取设备类型ID错误,  设备类型:{deviceType}");
                return 0;
            }
        }

        /// <summary>
        /// 获取操作ID
        /// </summary>
        /// <param name="describes"></param>
        /// <returns></returns>
        private static int GetOperateID(dynamic describes)
        {
            if (describes == null) { return 0; }
            var model = OperateItemModels.FirstOrDefault(x => x.Describes == describes);
            if (model != null)
            {
                return model.Id;
            }
            else
            {
                MessageBox.Show(messageBoxText: $"获取操作ID错误,  操作类型:{describes}");

                return 0;
            }

        }
        #endregion


        private void BtnSubmit_Click(object sender, RoutedEventArgs e)
        {

        }

        /// <summary>
        /// 任务列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnTask_Click(object sender, RoutedEventArgs e)
        {
            Button button = e.OriginalSource as Button;
            switch (button.Content.ToString())
            {
                case "新建":
                    if (this.SelectedTestQuestion == null)
                    {
                        return;
                    }
                    TestQuestionTaskViewModel viewModel = new TestQuestionTaskViewModel()
                    {
                        TestId = this.SelectedTestQuestion.Id,
                        Order = this.TestQuestionTaskList.Count > 0 ? this.TestQuestionTaskList.Max(p => p.Order) + 1 : 1
                    };
                    TestQuestionTaskEdit testQuestionEdit = new TestQuestionTaskEdit(viewModel, this.SelectedTestQuestion);
                    if (testQuestionEdit.ShowDialog() == true)
                    {
                        var StepList = Paper_TestQuestion_Task_StepDAL.GetMyPaper_TestQuestion_Task_StepModel(viewModel.Id);
                        foreach (var question in StepList)
                        {
                            viewModel.TestQuestionTaskStepList.Add(new TestQuestionTaskStepViewModel(question));
                        }
                        this.TestQuestionTaskList.Add(viewModel);
                    }
                    break;
                case "修改":
                    if (this.SelectedTestQuestionTask == null)
                    {
                        return;
                    }
                    TestQuestionTaskEdit testQuestionEdit1 = new TestQuestionTaskEdit(this.SelectedTestQuestionTask, this.SelectedTestQuestion);
                    testQuestionEdit1.ShowDialog();
                    break;
                case "删除":
                    if (this.SelectedTestQuestionTask != null && MessageBox.Show("确定删除任务？", "询问", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        if (Paper_TestQuestion_TaskDAL.DeleteByID(this.SelectedTestQuestionTask.Id) > 0)
                        {
                            this.TestQuestionTaskList.Remove(this.SelectedTestQuestionTask);
                        }
                    }
                    break;
                case "粘贴":
                    TaskCopy(Tasksneedcopy, this.SelectedTestQuestionTask);
                    Tasksneedcopy.Clear();
                    break;
                case "复制":
                    this.TaskCanCopyflag = true;
                    Tasksneedcopy.Add(this.SelectedTestQuestionTask);
                    break;
                case "取消":
                    this.TaskCanCopyflag = false;
                    Tasksneedcopy.Clear();
                    break;
            }
        }

        private void BtnStep_Click(object sender, RoutedEventArgs e)
        {
            Button button = e.OriginalSource as Button;
            switch (button.Content.ToString())
            {
                case "新建":
                    if (this.SelectedTestQuestionTask == null)
                    {
                        return;
                    }
                    TestQuestionTaskStepViewModel viewModel = new TestQuestionTaskStepViewModel()
                    {
                        TaskId = this.SelectedTestQuestionTask.Id,
                        //   Order = this.SelectedTestQuestionTask.TestQuestionTaskStepList.Count > 0 ? this.SelectedTestQuestionTask.TestQuestionTaskStepList.Max(p => p.Order) + 1 : 1
                    };
                    TestQuestionTaskStepEdit testQuestionEdit = new TestQuestionTaskStepEdit(viewModel, this.SelectedTestQuestion);
                    if (testQuestionEdit.ShowDialog() == true)
                    {
                        this.SelectedTestQuestionTask.TestQuestionTaskStepList.Add(viewModel);
                    }
                    break;
                case "修改":
                    if (this.SelectedTestQuestionTaskStep == null)
                    {
                        return;
                    }
                    TestQuestionTaskStepEdit testQuestionEdit1 = new TestQuestionTaskStepEdit(this.SelectedTestQuestionTaskStep, this.SelectedTestQuestion);
                    testQuestionEdit1.ShowDialog();
                    break;
                case "删除":
                    if (this.SelectedTestQuestionTaskStep == null)
                    {
                        return;
                    }
                    if (Paper_TestQuestion_Task_StepDAL.DeleteByID(this.SelectedTestQuestionTaskStep.Id) > 0)
                    {
                        this.SelectedTestQuestionTask.TestQuestionTaskStepList.Remove(this.SelectedTestQuestionTaskStep);
                    }
                    break;
                case "粘贴":
                    StepCopy(Stepsneedcopy);
                    break;
                case "复制":
                    this.StepCanCopyflag = true;
                    Stepsneedcopy.Add(this.SelectedTestQuestionTaskStep);
                    break;
                case "取消":
                    this.StepCanCopyflag = false;
                    Stepsneedcopy.Clear();
                    break;
            }
        }

        private void Chk_Checked(object sender, RoutedEventArgs e)
        {
            this.PaperList.Where(p => p.Id != this.SelectedTestPaper.Id).ToList().ForEach(p => p.Choose = false);
            //MainWindowNew.ChooseTestPaper = this.SelectedTestPaper;
        }
        /// <summary>
        /// 双击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DgTiming_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.SelectedTestQuestion == null) return;
            TestQuestionEdit testQuestionEdit = new TestQuestionEdit(this.SelectedTestQuestion, this.PaperList, this.QuestionList, !this.ManageMode);
            testQuestionEdit.ShowDialog();
        }

        private void DgSubmit_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

        }

        private void DgTask_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.SelectedTestQuestionTask == null) return;
            TestQuestionTaskEdit testQuestionEdit = new TestQuestionTaskEdit(this.SelectedTestQuestionTask, this.SelectedTestQuestion, !this.ManageMode);
            testQuestionEdit.ShowDialog();
        }

        private void DgStep_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.SelectedTestQuestionTaskStep == null) return;
            TestQuestionTaskStepEdit testQuestionEdit = new TestQuestionTaskStepEdit(this.SelectedTestQuestionTaskStep, this.SelectedTestQuestion, !this.ManageMode);
            testQuestionEdit.ShowDialog();
        }

        private void Chk_Click(object sender, RoutedEventArgs e)
        {
            if (this.SelectedTestPaper == null)
            {
                MessageBox.Show("请先选择试卷，再勾选场景！");
                return;
            }
        }

        private void BtnRef_Click(object sender, RoutedEventArgs e)
        {
            this.PaperList = new ObservableCollection<TestPaperViewModel>();
            this.QuestionList = new ObservableCollection<TestQuestionViewModel>();
            this.ShowQuestionList = new ObservableCollection<TestQuestionViewModel>();
            this.RefDate();
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.SelectedTestPaper != null && combolevel.SelectedItem != null)
            {
                if (combolevel.SelectedItem.ToString().Substring(38, 1) != "全")
                {
                    this.SelectedTestPaper.Level = combolevel.SelectedItem.ToString().Substring(38, 1);
                }
            }
            else if (combolevel.SelectedItem != null && combolevel.SelectedItem.ToString().Substring(38, 1) == "全")
            {
                QueryPaperList = PaperDAL.GetAll();
                this.PaperList.Clear();
                foreach (var model in QueryPaperList)
                {
                    if (this.PaperList.Where(p => p.Id == model.Id).Count() == 0)
                        this.PaperList.Add(new TestPaperViewModel(model));
                }
            }
            else if (combolevel.SelectedItem != null && combolevel.SelectedItem.ToString().Substring(38, 1) == "无")
            {
                QueryPaperList = PaperDAL.GetByLevel("");
                this.PaperList.Clear();
                foreach (var model in QueryPaperList)
                {
                    if (this.PaperList.Where(p => p.Id == model.Id).Count() == 0)
                        this.PaperList.Add(new TestPaperViewModel(model));
                }
            }
            else if (combolevel.SelectedItem != null)
            {
                QueryPaperList = PaperDAL.GetByLevel(combolevel.SelectedItem.ToString().Substring(38, 1));
                this.PaperList.Clear();
                foreach (var model in QueryPaperList)
                {
                    if (this.PaperList.Where(p => p.Id == model.Id).Count() == 0)
                        this.PaperList.Add(new TestPaperViewModel(model));
                }
            }
        }

        private void SearchPaperName_GotFocus(object sender, RoutedEventArgs e)
        {
            this.IsSelected = true;
        }

        private void SearchPaperName_LostFocus(object sender, RoutedEventArgs e)
        {
            this.IsSelected = false;
        }

        private void dgTiming_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (this.SelectedTestQuestion != null)
            {
                this.TestQuestionTaskList.Clear();
                SelectedTestQuestion.TestQuestionTasks = Paper_TestQuestion_TaskDAL.GetMyPaper_TestQuestion_TaskModel(SelectedTestQuestion.Id);
                foreach (var question in this.SelectedTestQuestion.TestQuestionTasks)
                {
                    this.TestQuestionTaskList.Add(new TestQuestionTaskViewModel(question));
                }

            }

            if (this.SelectedTestQuestion != null)
            {
                List<Paper_TestQuestion_Task_StepModel> steplist = new List<Paper_TestQuestion_Task_StepModel>();
                steplist = Paper_TestQuestion_Task_StepDAL.GetMyPaper_TestQuestion_Task_StepModel(this.SelectedTestQuestion.Id);
                TestPaper.TestQuestionTaskStepList.Clear();
                foreach (var step in steplist)
                {
                    TestPaper.TestQuestionTaskStepList.Add(new TestQuestionTaskStepViewModel(step));
                }
                this.VoicelibraryViewList.Clear();

            };

        }
        private void dgTask_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (this.SelectedTestQuestionTask != null)
            {
                SelectedTestQuestionTask.TestQuestionTaskStepList = new ObservableCollection<TestQuestionTaskStepViewModel>();
                SelectedTestQuestionTask.TestQuestionTaskStepList.Clear();
                var steps = Paper_TestQuestion_Task_StepDAL.GetMyPaper_TestQuestion_Task_StepModel(SelectedTestQuestionTask.Id);
                if (steps != null)
                {
                    foreach (var step in steps)
                    {
                        SelectedTestQuestionTask.TestQuestionTaskStepList.Add(new TestQuestionTaskStepViewModel(step));
                    }
                }
            }
        }
        /// <summary>
        /// 任务列表复制
        /// </summary>
        /// <param name="oldviewmodel"></param>
        /// <param name="newViewmdole"></param>
        public void TaskCopy(List<TestQuestionTaskViewModel> oldviewmodel, TestQuestionTaskViewModel newViewmdole)//复制任务方法 Add by gy
        {
            Dictionary<string, bool> dicTrainPosition = new Dictionary<string, bool>();
            Dictionary<int, int> dicBefore = new Dictionary<int, int>();
            Dictionary<string, int> dicDevState = new Dictionary<string, int>();
            foreach (var needcopy in oldviewmodel)
            {
                dicTrainPosition.Clear();
                dicBefore.Clear();
                dicDevState.Clear();
                this.TaskTrainPositionList.Clear();
                this.TaskBeforeList.Clear();
                this.TaskDevStateList.Clear();

                if (TaskCanCopyflag = false)
                {
                    return;
                }
                if (needcopy == null)
                {
                    return;
                }
                TestQuestionTaskViewModel viewModelcopy = new TestQuestionTaskViewModel()
                {
                    TestId = newViewmdole.TestId,
                    Order = needcopy.Order,
                    Describes = needcopy.Describes,
                    MutexTask = needcopy.MutexTask,
                    AfterTask = needcopy.AfterTask,
                    AfterInterval = needcopy.AfterInterval,
                    UIOrder = needcopy.UIOrder,
                    TaskType = needcopy.TaskType
                };

                viewModelcopy.Order = this.SelectedTestQuestion.TestQuestionTasks.Count > 0 ? this.SelectedTestQuestion.TestQuestionTasks.Max(p => p.Order) + 1 : 1;

                if (needcopy != null)
                {
                    foreach (var param in this.TaskTrainPositionList)
                    {
                        if (param.DevTrainID == 0 || param.DevAreaID == 0) continue;
                        dicTrainPosition.Add(param.DevTrainID + "|" + param.DevAreaID, param.IsStop);
                    }

                    foreach (var param in this.TaskBeforeList)
                    {
                        if (param.StepID == 0) continue;
                        dicBefore.Add(param.StepID, param.Delay);
                    }

                    foreach (var param in this.TaskDevStateList)
                    {
                        if (param.DevType == 0 || param.DevID == 0) continue;
                        dicDevState.Add(param.DevType + "|" + param.DevID, param.DevStateID);
                    }


                    if (viewModelcopy.Id == 0)
                    {
                        int newId = Paper_TestQuestion_TaskDAL.Insert(viewModelcopy.Model);
                        if (newId > 0)
                        {
                            viewModelcopy.Id = newId;
                            var oldStepList = Paper_TestQuestion_Task_StepDAL.GetMyPaper_TestQuestion_Task_StepModel(needcopy.Id);
                            foreach (var question in oldStepList)
                            {
                                viewModelcopy.TestQuestionTaskStepList.Add(new TestQuestionTaskStepViewModel(question));
                            }
                            foreach (var stepviewmodel in viewModelcopy.TestQuestionTaskStepList)
                            {
                                stepviewmodel.TaskId = viewModelcopy.Id;
                                var insertID = Paper_TestQuestion_Task_StepDAL.Insert(stepviewmodel.Model);
                                if (insertID > 0)
                                {
                                    stepviewmodel.Id = insertID;
                                }
                            }

                        }
                        var StepList = Paper_TestQuestion_Task_StepDAL.GetMyPaper_TestQuestion_Task_StepModel(viewModelcopy.Id);
                        foreach (var question in StepList)
                        {
                            viewModelcopy.TestQuestionTaskStepList.Add(new TestQuestionTaskStepViewModel(question));
                        }
                        this.TestQuestionTaskList.Add(viewModelcopy);
                    }

                }
            }
        }

        /// <summary>
        /// 步骤列表的复制
        /// </summary>
        /// <param name="oldviewmodel"></param>
        public void StepCopy(List<TestQuestionTaskStepViewModel> oldviewmodel)//复制步骤方法 Add by gy
        {
            foreach (var needcopy in oldviewmodel)
            {
                PrerequisiteJson = new PrerequisiteJson();

                if (!string.IsNullOrWhiteSpace(needcopy.Prerequisite) && needcopy.Prerequisite.Contains(';'))
                {
                    PrerequisiteJson prerequisite = JsonConvert.DeserializeObject<PrerequisiteJson>(needcopy.Prerequisite);
                    this.PrerequisiteJson.beforeSteps = prerequisite.beforeSteps;
                    this.PrerequisiteJson.trainPositions = prerequisite.trainPositions;
                    this.PrerequisiteJson.intervalMonitors = prerequisite.intervalMonitors;
                    this.PrerequisiteJson.parameters = prerequisite.parameters;
                }
                if (StepCanCopyflag = false)
                {
                    return;
                }
                if (needcopy == null)
                {
                    return;
                }
                TestQuestionTaskStepViewModel viewModelcopy = new TestQuestionTaskStepViewModel()
                {
                    //TestQuestionTaskStepID = needcopy.TestQuestionTaskStepID,
                    Id = 0,
                    TaskId = needcopy.TaskId,
                    OperateId = needcopy.OperateId,
                    Score = needcopy.Score,
                    Parameter = needcopy.Parameter,
                    SysType = needcopy.SysType,
                    TaskType = needcopy.TaskType,
                    Describes = needcopy.Describes,
                    DeviceTypeId = needcopy.DeviceTypeId,
                    DeviceId = needcopy.DeviceId,
                    StepContent = needcopy.StepContent,
                    Prerequisite = needcopy.Prerequisite,
                    KeyWords = needcopy.KeyWords,
                    TimeOut = needcopy.TimeOut,
                    Duration = needcopy.Duration,
                    IsContinued = needcopy.IsContinued,
                    RoleId = needcopy.RoleId,
                    IsMultStep = needcopy.IsMultStep,
                };

                if (needcopy != null)
                {
                    //viewModelcopy.Prerequisite = JsonConvert.SerializeObject(needcopy.);

                    if (viewModelcopy.Id == 0)
                    {
                        viewModelcopy.TaskId = this.SelectedTestQuestionTask.Id;
                        int newId = 0;
                        if (Paper_TestQuestion_Task_StepDAL.Insert(viewModelcopy.Model) > 0)
                        {
                            viewModelcopy.Id = newId;
                        }
                    }
                    this.SelectedTestQuestionTask.TestQuestionTaskStepList.Add(viewModelcopy);
                }
            }
        }

        private void VoiceBox_Click(object sender, RoutedEventArgs e)
        {
            if (this.SelectedVoicelibrary.IsChecked)
            {

            }
        }
        /// <summary>
        ///修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void VoiceSP_Click(object sender, RoutedEventArgs e)
        {
            //if (this.SelectedTestQuestion == null)
            //{
            //    MessageBox.Show("请先选择场景！");
            //    return;
            //}
            //TestVoiceLibrary voiceLibrary = new TestVoiceLibrary(VoicelibraryViewList);
            //voiceLibrary.ShowDialog();
        }
        #region 表格拖拽
        //行号
        int prevRowIndex = -1;
        Point TargetMousePoint;
        TestQuestionTaskStepViewModel selectedEmp;
        public ObservableCollection<TestQuestionTaskStepViewModel> stepViewModels { get; set; } = new ObservableCollection<TestQuestionTaskStepViewModel>();
        /// <summary>
        /// 拖拽排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgStep_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                prevRowIndex = GetDataGridItemCurrentRowIndex(e.GetPosition, dgStep);
                if (prevRowIndex < 0) return;
                //如果选中区域在第一列，即点击选择框，则不进行
                if (e.GetPosition(this.dgStep).X < 30) return;
                selectedEmp = dgStep.Items[prevRowIndex] as TestQuestionTaskStepViewModel;

                if (selectedEmp == null) return;
                DragDropEffects dragdropeffects = DragDropEffects.Move;
                SelectedTestQuestionTaskStep = selectedEmp;
                if (DragDrop.DoDragDrop(dgStep, selectedEmp, dragdropeffects)
                                    != DragDropEffects.None)
                {
                    dgStep.SelectedItem = selectedEmp;
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void dgStep_DragOver(object sender, DragEventArgs e)
        {
            try
            {
                int index = GetDataGridItemCurrentRowIndex(e.GetPosition, dgStep);
                for (int i = 0; i < dgStep.Items.Count; i++)
                {
                    DataGridRow r = dgStep.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow;
                    if (i != index)
                    {
                        r.BorderBrush = new SolidColorBrush(Colors.Transparent);
                        r.BorderThickness = new Thickness(0, 0, 0, 0);
                    }
                    else
                    {
                        r.BorderBrush = new SolidColorBrush(Color.FromRgb(32, 164, 230));
                        Thickness th = new Thickness(0, 0, 0, 0);
                        if (index > prevRowIndex) th = new Thickness(0, 0, 0, 1);
                        else if (index < prevRowIndex) th = new Thickness(0, 1, 0, 0);
                        r.BorderThickness = th;
                    }
                }
                if (!popStep.IsOpen)
                {
                    popStep.IsOpen = true;
                }
                Size popupSize = new Size(popStep.ActualWidth + 110, popStep.ActualHeight + 10);
                Point p = e.GetPosition(canvas); ;
                p.X += 10;
                popStep.PlacementRectangle = new Rect(p, popupSize);
            }
            catch (Exception ex)
            {
            }
        }

        private void dgStep_Drop(object sender, DragEventArgs e)
        {
            try
            {
                this.popStep.IsOpen = false;
                int index = GetDataGridItemCurrentRowIndex(e.GetPosition, dgStep);
                if (index < 0 || index == prevRowIndex) return;
                (dgStep.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow).BorderThickness = new Thickness(0, 0, 0, 0);
                if (index >= dgStep.Items.Count - 1)
                {
                    index = dgStep.Items.Count - 1;
                }

                SelectedTestQuestionTask.TestQuestionTaskStepList.RemoveAt(prevRowIndex);
                SelectedTestQuestionTask.TestQuestionTaskStepList.Insert(index, selectedEmp);
                stepViewModels.Clear();
                stepViewModels = new ObservableCollection<TestQuestionTaskStepViewModel>();

                int UI = 1;
                //保存到数据库
                foreach (TestQuestionTaskStepViewModel param in SelectedTestQuestionTask.TestQuestionTaskStepList)
                {
                    Paper_TestQuestion_Task_StepModel taskStepModel = new Paper_TestQuestion_Task_StepModel();
                    taskStepModel.Id = param.Id;
                    taskStepModel.TaskId = param.TaskId;
                    taskStepModel.OperateId = param.OperateId;
                    taskStepModel.Parameter = param.Parameter;
                    taskStepModel.Score = param.Score;
                    taskStepModel.SysType = param.SysType;
                    taskStepModel.TaskType = param.TaskType;
                    taskStepModel.Describes = param.Describes;
                    taskStepModel.DevicetypeId = param.DeviceTypeId;
                    taskStepModel.DeviceId = param.DeviceId;
                    taskStepModel.StepContent = param.StepContent;
                    taskStepModel.Prerequisite = param.Prerequisite;
                    taskStepModel.KeyWords = param.KeyWords;
                    taskStepModel.TimeOut = param.TimeOut;
                    taskStepModel.Duration = param.Duration;
                    taskStepModel.IsContinued = param.IsContinued ? "1" : "0";
                    taskStepModel.RoleId = param.RoleId;
                    taskStepModel.MutexStepId = param.IsMultStep ? 1 : 0;
                    taskStepModel.UIOrder = UI;
                    param.UIOrder = UI;
                    stepViewModels.Add(param);
                    Paper_TestQuestion_Task_StepDAL.Update(taskStepModel);
                    UI++;
                }
                // stepViewModels.ToList().OrderBy(t => t.UIOrder);
                SelectedTestQuestionTask.TestQuestionTaskStepList = new ObservableCollection<TestQuestionTaskStepViewModel>();
                var varss = new ObservableCollection<TestQuestionTaskStepViewModel>(stepViewModels.ToList().OrderBy(t => t.UIOrder));
                SelectedTestQuestionTask.TestQuestionTaskStepList = varss;
                e.Handled = true;
                prevRowIndex = -1;
            }
            catch (Exception ex)
            {

            }
        }

        private void dgStep_DragLeave(object sender, DragEventArgs e)
        {
            this.popStep.IsOpen = false;
        }
        public delegate Point GetDragDropPosition(IInputElement theElement);
        /// Returns the Index of the Current Row.
        /// </summary>
        /// <param name="pos"></param>
        /// <returns></returns>
        public int GetDataGridItemCurrentRowIndex(GetDragDropPosition pos, DataGrid dgEmployee)
        {
            int curIndex = -1;
            for (int i = 0; i < dgEmployee.Items.Count; i++)
            {
                DataGridRow itm = GetDataGridRowItem(i, dgEmployee);
                if (IsTheMouseOnTargetRow(itm, pos))
                {
                    curIndex = i;
                    break;
                }
            }
            return curIndex;
        }
        /// <summary>
        /// Returns the selected DataGridRow
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        private DataGridRow GetDataGridRowItem(int index, DataGrid dgEmployee)
        {
            if (dgEmployee.ItemContainerGenerator.Status
                    != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
                return null;

            return dgEmployee.ItemContainerGenerator.ContainerFromIndex(index)
                                                            as DataGridRow;
        }
        private bool IsTheMouseOnTargetRow(Visual theTarget, GetDragDropPosition pos)
        {
            Rect posBounds = VisualTreeHelper.GetDescendantBounds(theTarget);
            Point theMousePos = pos((IInputElement)theTarget);
            return posBounds.Contains(theMousePos);
        }
        #endregion

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox search = sender as TextBox;
            if (search != null)
            {
                ShowQuestionList = new ObservableCollection<TestQuestionViewModel>(QuestionList.Where(x => x.TestName.Contains(search.Text)));
            }
        }

        /// <summary>
        /// 线路筛选栏改变时修改全局变量RefLineName 并添加车站Combox中的值
        /// add by peizhankun
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TestVisibleLineComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            List<DeviceModel> AllStationDevice = DeviceDAL.GetDeviceByDeviceType(5);
            var Cbx = e.Source as ComboBox;
            if (Cbx.SelectedItem.ToString().Contains("全部"))
            {
                DebugAllLine = true;
            }
            else
            {
                foreach (LineNameEnum line in Enum.GetValues(typeof(LineNameEnum)))
                {
                    DebugAllLine = false;
                    if (Cbx.SelectedItem.ToString().Contains(GetLineNameAttribute(line)))
                    {
                        RefLineName = line.ToString();
                    }
                }
            }

            this.PaperList.Clear();
            this.QuestionList.Clear();
            this.ShowQuestionList.Clear();
            this.RefDate();
            lock (lineBlock)
            {
                this.TestVisibleStationComboBox.Items.Clear();
                this.TestVisibleStationComboBox.Items.Add("全部");
                foreach (var station in AllStationDevice)
                {
                    if (station.LineName == RefLineName)
                    {
                        this.TestVisibleStationComboBox.Items.Add(station.DeviceName);
                    }
                }
            }
        }

        public static string GetLineNameAttribute(LineNameEnum value)
        {
            var fieldInfo = value.GetType().GetField(value.ToString());
            var attribute = fieldInfo.GetCustomAttribute(typeof(LineNameAttribute), false) as LineNameAttribute;
            if (attribute.Name != null)
                return attribute.Name;
            return null;
        }

        public LineNameEnum? GetLineNameEnum(string value)
        {

            foreach (LineNameEnum a in Enum.GetValues(typeof(LineNameEnum)))
            {
                var feildInfo = a.GetType().GetField(a.ToString());
                var attribute = feildInfo.GetCustomAttribute(typeof(LineNameAttribute), false) as LineNameAttribute;
                if (attribute != null && attribute.Name == value)
                {
                    return a;
                }
            }
            return null;
        }

        private void TestVisibleStationComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }


    public class TestPaperViewModel : NotifyPropertyChanged
    {
        public int Id { get; set; }
        public DateTime CreateTime { get; set; }
        private DateTime m_UpdateTime;
        public DateTime UpdateTime
        {
            get
            {
                return this.m_UpdateTime;
            }
            set
            {
                this.m_UpdateTime = value;
                this.OnPropertyChanged();
            }
        }
        public decimal TotalScore { get; set; }

        private string m_Describes;

        public string Describes
        {
            get
            {
                return this.m_Describes;
            }
            set
            {
                this.m_Describes = value;
                this.OnPropertyChanged();
            }
        }
        private string m_Level;

        public string Level
        {
            get
            {
                return this.m_Level;
            }
            set
            {
                this.m_Level = value;
                this.OnPropertyChanged();
            }
        }
        private string m_TesQuestiontList;

        public string TesQuestiontList
        {
            get
            {
                return this.m_TesQuestiontList;
            }
            set
            {
                this.m_TesQuestiontList = value;
                this.OnPropertyChanged();
            }
        }

        private bool m_Choose;

        public bool Choose
        {
            get
            {
                return this.m_Choose;
            }
            set
            {
                this.m_Choose = value;
                this.OnPropertyChanged();
            }
        }

        public PaperModel Model
        {
            get
            {
                return new PaperModel()
                {
                    Id = this.Id,
                    CreateTime = this.CreateTime,
                    Describes = this.Describes,
                    UpdateTime = this.UpdateTime,
                    TotalScore = this.TotalScore,
                    TesquestiontList = this.TesQuestiontList,
                    TestQuestions = this.TestQuestions,
                    Level = this.Level
                };
            }
        }

        public TestPaperViewModel()
        {

        }

        public TestPaperViewModel(PaperModel model)
        {
            this.Id = model.Id;
            this.CreateTime = model.CreateTime;
            this.UpdateTime = model.UpdateTime;
            this.TotalScore = model.TotalScore;
            this.Describes = model.Describes;
            this.Level = model.Level;
            this.TesQuestiontList = model.TesquestiontList;
            this.TestQuestions = model.TestQuestions;

        }

        public List<Paper_TestQuestionModel> TestQuestions { get; set; } = new List<Paper_TestQuestionModel>();
    }

    public class TestQuestionViewModel : NotifyPropertyChanged
    {
        public int Id { get; set; }
        /// <summary>
        /// 试卷名称
        /// </summary>

        private string m_TestName;
        public string TestName
        {
            get
            {
                return this.m_TestName;
            }
            set
            {
                this.m_TestName = value;
                this.OnPropertyChanged();
            }
        }
        public string AllDescribe
        {
            get { return "【" + this.Id + "】" + this.TestName; }
        }
        /// <summary>
        /// 试卷考试时长;单位：秒
        /// </summary>
        private int m_CountDown;
        public int CountDown
        {
            get
            {
                return this.m_CountDown;
            }
            set
            {
                this.m_CountDown = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 创建时间
        /// </summary>
        private DateTime m_CreateTime;
        public DateTime CreateTime
        {
            get
            {
                return this.m_CreateTime;
            }
            set
            {
                this.m_CreateTime = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 更新时间
        /// </summary>
        private DateTime m_UpdateTime;
        public DateTime UpdateTime
        {
            get
            {
                return this.m_UpdateTime;
            }
            set
            {
                this.m_UpdateTime = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 场景文件
        /// </summary>
        private int m_SceneFile;
        public int SceneFile
        {
            get
            {
                return this.m_SceneFile;
            }
            set
            {
                this.m_SceneFile = value;
                this.OnPropertyChanged();
                this.SceneFileUpload = this.m_SceneFile != null && this.m_SceneFile > 0 ? "已上传" : "未上传";

            }
        }

        private string m_SceneFileName;//场景文件名
        public string SceneFileName
        {
            get
            {
                return this.m_SceneFileName;
            }
            set
            {
                this.m_SceneFileName = value;
                this.OnPropertyChanged();
            }
        }
        public static List<postModel> roleModels { get; set; } = PostDAL.GetPostInfo();
        private string m_Roles;
        public string Roles
        {
            get
            {
                return this.m_Roles;
            }
            set
            {
                this.m_Roles = value;
                this.OnPropertyChanged();
                if (!string.IsNullOrWhiteSpace(Roles))
                {
                    //long num = 0;
                    //long.TryParse(Roles, out num);
                    //this.RoleName = ((RoleItemEnum)num).ToString();
                    var roleModel = roleModels.FirstOrDefault(x => x.post_id == Roles);
                    string roleName = roleModel == null ? "" : roleModel.post_name;
                    this.RoleName = roleName;
                }
            }
        }

        private string m_RoleName;
        public string RoleName
        {
            get
            {
                return this.m_RoleName;
            }
            set
            {
                this.m_RoleName = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// Describe
        /// </summary>
        private string m_Describes;
        public string Describes
        {
            get
            {
                return this.m_Describes;
            }
            set
            {
                this.m_Describes = value;
                this.OnPropertyChanged();
            }
        }

        private string m_SceneFileUpload = "未上传";
        public string SceneFileUpload
        {
            get
            {
                return this.m_SceneFileUpload;
            }
            set
            {
                this.m_SceneFileUpload = value;
                this.OnPropertyChanged();
            }
        }

        private bool m_IsChecked;
        public bool IsChecked
        {
            get
            {
                return this.m_IsChecked;
            }
            set
            {
                this.m_IsChecked = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 是否为主场景
        /// </summary>
        private string m_IsMain;
        public string IsMain
        {
            get
            {
                return this.m_IsMain;
            }
            set
            {
                this.m_IsMain = value;
                this.OnPropertyChanged();
            }
        }

        private bool isFAOScene;
        /// <summary>
        /// 场景类型
        /// </summary>
        public bool IsFAOScene
        {
            get
            {
                return isFAOScene;
            }
            set
            {
                this.isFAOScene = value;
                OnPropertyChanged();
            }
        }
        /// <summary>
        /// 附场景
        /// </summary>
        private string m_AttachQuestion;
        public string AttachQuestion
        {
            get
            {
                return this.m_AttachQuestion;
            }
            set
            {
                this.m_AttachQuestion = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 停运分数
        /// </summary>
        private decimal m_SuspensionScore;
        public decimal SuspensionScore
        {
            get
            {
                return this.m_SuspensionScore;
            }
            set
            {
                this.m_SuspensionScore = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 晚点分数
        /// </summary>
        private decimal m_LateScore;
        public decimal LateScore
        {
            get
            {
                return this.m_LateScore;
            }
            set
            {
                this.m_LateScore = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 迫停分数
        /// </summary>
        private decimal m_StopScore;
        public decimal StopScore
        {
            get
            {
                return this.m_StopScore;
            }
            set
            {
                this.m_StopScore = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 提交元素分数
        /// </summary>
        private decimal m_SubmitScore;
        public decimal SubmitScore
        {
            get
            {
                return this.m_SubmitScore;
            }
            set
            {
                this.m_SubmitScore = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 所占分数百分比
        /// </summary>
        private decimal m_Percent;
        public decimal Percent
        {
            get
            {
                return this.m_Percent;
            }
            set
            {
                this.m_Percent = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 试卷分数
        /// </summary>
        private string m_TotalScore;
        public string TotalScore
        {
            get
            {
                return this.m_TotalScore;
            }
            set
            {
                this.m_TotalScore = value;
                this.OnPropertyChanged();
            }
        }

        private string m_MinusPoints;
        public string MinusPoints
        {
            get
            {
                return this.m_MinusPoints;
            }
            set
            {
                this.m_MinusPoints = value;
                this.OnPropertyChanged();
            }
        }

        private int m_StationID;
        public int StationID
        {
            get
            {
                return this.m_StationID;
            }
            set
            {
                this.m_StationID = value;
                this.OnPropertyChanged();
            }
        }
        private int m_WaitCountDown;
        public int WaitCountDown
        {
            get
            {
                return this.m_WaitCountDown;
            }
            set
            {
                this.m_WaitCountDown = value;
                this.OnPropertyChanged();
            }
        }
        private decimal m_StopLaterScore;
        public decimal StopLaterScore
        {
            get
            {
                return this.m_StopLaterScore;
            }
            set
            {
                this.m_StopLaterScore = value;
                this.OnPropertyChanged();
            }
        }

        private decimal m_SubmitElementScore;
        public decimal SubmitElementScore
        {
            get
            {
                return this.m_SubmitElementScore;
            }
            set
            {
                this.m_SubmitElementScore = value;
                this.OnPropertyChanged();
            }
        }

        public String TestPaperTotal { get; set; }
        public List<Paper_TestQuestion_TaskModel> TestQuestionTasks { get; set; }

        public Paper_TestQuestionModel Model
        {
            get
            {
                return new Paper_TestQuestionModel()
                {
                    Id = this.Id,
                    TestName = this.TestName,
                    CountDown = this.CountDown,
                    Describes = this.Describes,
                    SceneFile = this.SceneFile,
                    CreateTime = this.CreateTime,
                    IsMain = this.IsMain,
                    AttachQuestion = this.AttachQuestion,
                    SuspensionScore = this.SuspensionScore,
                    LateScore = this.LateScore,
                    StopScore = this.StopScore,
                    SubmitScore = this.SubmitScore,
                    Percent = this.Percent,
                    TotalScore = this.TotalScore,
                    UpdateTime = this.UpdateTime,
                    Roles = this.Roles,
                    StationId = this.StationID,
                    SceneType = this.IsFAOScene ? "FAO" : "CBTC",
                };
            }
        }

        public TestQuestionViewModel()
        {

        }

        public TestQuestionViewModel(Paper_TestQuestionModel model)
        {
            this.Id = model.Id;
            this.TestName = model.TestName;
            this.CountDown = model.CountDown;
            this.Describes = model.Describes;
            this.SceneFile = model.SceneFile;
            this.CreateTime = model.CreateTime;
            this.IsMain = model.IsMain;
            this.AttachQuestion = model.AttachQuestion;
            this.SuspensionScore = model.SuspensionScore;
            this.LateScore = model.LateScore;
            this.StopScore = model.StopScore;
            this.SubmitScore = model.SubmitScore;
            this.Percent = model.Percent;
            this.TotalScore = model.TotalScore;
            this.UpdateTime = model.UpdateTime;
            this.Roles = model.Roles;
            this.StationID = model.StationId;
            this.IsFAOScene = model.SceneType == "FAO";
        }

    }


    public class TestQuestionTaskViewModel : NotifyPropertyChanged
    {
        public int Id { get; set; }
        public int TestId { get; set; }



        private string m_Describes;
        public string Describes
        {
            get
            {
                return this.m_Describes;
            }
            set
            {
                this.m_Describes = value;
                this.OnPropertyChanged();
            }
        }
        public string AllDescribe
        {
            get { return "【" + this.Id + "】" + this.Describes; }
        }

        private int m_MutexTask;
        public int MutexTask
        {
            get
            {
                return this.m_MutexTask;
            }
            set
            {
                this.m_MutexTask = value;
                this.OnPropertyChanged();
            }
        }

        private int m_AfterTask;
        public int AfterTask
        {
            get
            {
                return this.m_AfterTask;
            }
            set
            {
                this.m_AfterTask = value;
                this.OnPropertyChanged();
            }
        }

        private int m_AfterInterval;
        public int AfterInterval
        {
            get
            {
                return this.m_AfterInterval;
            }
            set
            {
                this.m_AfterInterval = value;
                this.OnPropertyChanged();
            }
        }
        private int m_Order;
        public int Order
        {
            get
            {
                return this.m_Order;
            }
            set
            {
                this.m_Order = value;
                this.OnPropertyChanged();
            }
        }
        private int m_UIOrder;
        /// <summary>
        /// 界面排序
        /// </summary>
        public int UIOrder
        {
            get
            {
                return this.m_UIOrder;
            }
            set
            {
                this.m_UIOrder = value;
                this.OnPropertyChanged();
            }
        }
        private string m_TaskType = "";
        /// <summary>
        /// 任务类型
        /// </summary>
        public string TaskType
        {
            get
            {
                return this.m_TaskType;
            }
            set
            {
                this.m_TaskType = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 场景文件
        /// </summary>
        private byte[] m_SceneFile;
        /// <summary>
        /// 任务类型
        /// </summary>
        public byte[] SceneFile
        {
            get
            {
                return this.m_SceneFile;
            }
            set
            {
                this.m_SceneFile = value;
                this.OnPropertyChanged();
            }
        }
        private bool m_IsMain;
        public bool IsMain
        {
            get
            {
                return this.m_IsMain;
            }
            set
            {
                this.m_IsMain = value;
                this.OnPropertyChanged();
            }
        }
        public Paper_TestQuestion_TaskModel Model
        {
            get
            {
                return new Paper_TestQuestion_TaskModel()
                {
                    Id = this.Id,
                    TestId = this.TestId,
                    Describes = this.Describes,
                    MutexTask = this.MutexTask,
                    AfterTask = this.AfterTask,
                    AfterInterval = this.AfterInterval,
                    Order = this.Order,
                    UiOrder = this.UIOrder,
                    TaskType = this.TaskType,
                    IsMain = this.IsMain,
                };
            }
        }

        public TestQuestionTaskViewModel()
        {

        }

        public TestQuestionTaskViewModel(Paper_TestQuestion_TaskModel model)
        {
            this.Id = model.Id;
            this.TestId = model.TestId;
            this.Describes = model.Describes;
            this.MutexTask = model.MutexTask;
            this.AfterTask = model.AfterTask;
            this.AfterInterval = model.AfterInterval;
            this.Order = model.Order;
            this.UIOrder = model.UiOrder;
            this.TaskType = model.TaskType;
            this.IsMain = model.IsMain;
        }
        private ObservableCollection<TestQuestionTaskStepViewModel> m_TestQuestionTaskStepList = new ObservableCollection<TestQuestionTaskStepViewModel>();
        public ObservableCollection<TestQuestionTaskStepViewModel> TestQuestionTaskStepList
        {
            get
            {
                return this.m_TestQuestionTaskStepList;
            }
            set
            {
                this.m_TestQuestionTaskStepList = value;
                this.OnPropertyChanged();
            }
        }
    }
    public class voicelibraryViewModel : NotifyPropertyChanged
    {
        /// <summary>
        /// 试卷表索引
        /// </summary>
        public int TestPaperID { get; set; }
        /// <summary>
        /// 场景表索引
        /// </summary>
        public int TestQuestionID { get; set; }

        private bool m_IsChecked;
        public bool IsChecked
        {
            get
            {
                return this.m_IsChecked;
            }
            set
            {
                this.m_IsChecked = value;
                this.OnPropertyChanged();
            }
        }
        private bool m_IsSelect;
        public bool IsSelect
        {
            get
            {
                return this.m_IsSelect;
            }
            set
            {
                this.m_IsSelect = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 序号
        /// </summary>
        private int id;
        public int ID
        {
            get
            {
                return this.id;
            }
            set
            {
                this.id = value;
                this.OnPropertyChanged();
            }
        }

        /// <summary>
        /// 命令对象
        /// </summary>
        private string m_CommandType;
        public string CommandType
        {
            get
            {
                return this.m_CommandType;
            }
            set
            {
                this.m_CommandType = value;
                this.OnPropertyChanged();
            }
        }

        /// <summary>
        /// 语音对象
        /// </summary>
        private string m_DevTypeName = "";
        public string DevTypeName
        {
            get
            {
                return this.m_DevTypeName;
            }
            set
            {
                this.m_DevTypeName = value;
                this.OnPropertyChanged();
            }
        }

        /// <summary>
        /// 语音详情
        /// </summary>
        private string m_TalkContent;
        public string TalkContent
        {
            get
            {
                return this.m_TalkContent;
            }
            set
            {
                this.m_TalkContent = value;
                this.OnPropertyChanged();
            }
        }


    }

    public class TestQuestionTaskStepViewModel : NotifyPropertyChanged
    {
        public int Id { get; set; }
        public int TaskId { get; set; }

        private int m_OperateId;
        public int OperateId
        {
            get
            {
                return this.m_OperateId;
            }
            set
            {
                this.m_OperateId = value;
                this.OnPropertyChanged();
                if (MainWindowNew.CurMainWindow.OperateitemList != null && OperateId != 0)
                    this.StepName = MainWindowNew.CurMainWindow.OperateitemList.FirstOrDefault(t => t.Id == OperateId).Describes;
            }
        }
        private string m_StepName = "";
        public string StepName
        {
            get
            {
                return this.m_StepName;
            }
            set
            {
                this.m_StepName = value;
                this.OnPropertyChanged();
            }
        }

        private string m_Parameter = "";
        public string Parameter
        {
            get
            {
                return this.m_Parameter;
            }
            set
            {
                this.m_Parameter = value;
                this.OnPropertyChanged();
            }
        }


        private decimal m_Score;
        public decimal Score
        {
            get
            {
                return this.m_Score;
            }
            set
            {
                this.m_Score = value;
                this.OnPropertyChanged();
            }
        }

        private string m_SysType;
        public string SysType
        {
            get
            {
                return this.m_SysType;
            }
            set
            {
                this.m_SysType = value;
                this.OnPropertyChanged();
            }
        }

        private string m_TaskType;
        public string TaskType
        {
            get
            {
                return this.m_TaskType;
            }
            set
            {
                this.m_TaskType = value;
                this.OnPropertyChanged();
            }
        }

        private string m_Describes;
        public string Describes
        {
            get
            {
                return this.m_Describes;
            }
            set
            {
                this.m_Describes = value;
                this.OnPropertyChanged();
            }
        }
        public string AllDescribe
        {
            get { return "【" + this.Id + "】" + this.Describes; }
        }

        private int m_DeviceTypeId;
        public int DeviceTypeId
        {
            get
            {
                return this.m_DeviceTypeId;
            }
            set
            {
                this.m_DeviceTypeId = value;
                this.OnPropertyChanged();
            }
        }

        private string m_DeviceId;
        public string DeviceId
        {
            get
            {
                return this.m_DeviceId;
            }
            set
            {
                this.m_DeviceId = value;
                this.OnPropertyChanged();
                if (!string.IsNullOrWhiteSpace(DeviceId))
                {
                    var devs = new List<DeviceModel>();
                    if (DeviceTypeId != 0)
                        devs.AddRange(MainWindowNew.DeviceList[DeviceTypeId]);
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in DeviceId.Split(','))
                    {
                        if (int.TryParse(item, out int num))
                        {
                            var dev = devs.FirstOrDefault(t => t.DeviceId == num);
                            if (dev != null)
                            {
                                var deviceName = dev.DeviceName;
                                sb.Append(deviceName).Append(",");
                            }
                        }
                    }
                    DeviceName = sb.ToString().TrimEnd(',');
                }
            }
        }
        private string m_DeviceName;
        public string DeviceName
        {
            get
            {
                return this.m_DeviceName;
            }
            set
            {
                this.m_DeviceName = value;
                this.OnPropertyChanged();
            }

        }

        private string m_StepContent;
        public string StepContent
        {
            get
            {
                return this.m_StepContent;
            }
            set
            {
                this.m_StepContent = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 前提条件;前提条件：以Json字符串格式保存
        /// </summary>
        private string m_Prerequisite;
        public string Prerequisite
        {
            get
            {
                return this.m_Prerequisite;
            }
            set
            {
                this.m_Prerequisite = value;
                this.OnPropertyChanged();
            }
        }

        private string m_KeyWords = "";
        public string KeyWords
        {
            get
            {
                return this.m_KeyWords;
            }
            set
            {
                this.m_KeyWords = value;
                this.OnPropertyChanged();
            }
        }

        private int m_TimeOut;
        public int TimeOut
        {
            get
            {
                return this.m_TimeOut;
            }
            set
            {
                this.m_TimeOut = value;
                this.OnPropertyChanged();
            }
        }

        private decimal m_Duration;
        public decimal Duration
        {
            get
            {
                return this.m_Duration;
            }
            set
            {
                this.m_Duration = value;
                this.OnPropertyChanged();
            }
        }



        private bool m_IsContinued;
        public bool IsContinued
        {
            get
            {
                return this.m_IsContinued;
            }
            set
            {
                this.m_IsContinued = value;
                this.OnPropertyChanged();
            }
        }
        public List<postModel> roleModels { get; set; } = PostDAL.GetPostInfo();

        private string m_RoleId;
        public string RoleId
        {
            get
            {
                return this.m_RoleId;
            }
            set
            {
                this.m_RoleId = value;
                this.OnPropertyChanged();
                if (!string.IsNullOrWhiteSpace(RoleId))
                {
                    List<string> roleNames = new List<string>();
                    List<string> roleIDList = RoleId.Split(',').ToList();
                    foreach (string roleID in roleIDList)
                    {
                        //long.TryParse(roleID, out long num);

                        var roleModel = roleModels.FirstOrDefault(x => x.post_id == roleID);
                        string roleName = roleModel == null ? "" : roleModel.post_name;
                        roleNames.Add(roleName);
                    }
                    this.RoleName = string.Join(",", roleNames);
                }

            }
        }

        private string m_RoleName;
        public string RoleName
        {
            get
            {
                return this.m_RoleName;
            }
            set
            {
                this.m_RoleName = value;
                this.OnPropertyChanged();
            }
        }
        private int m_UIOrder;
        public int UIOrder
        {
            get
            {
                return this.m_UIOrder;
            }
            set
            {
                this.m_UIOrder = value;
                this.OnPropertyChanged();
            }
        }

        private bool isMultStep;
        public bool IsMultStep
        {
            get
            {
                return isMultStep;
            }
            set
            {
                isMultStep = value;
                this.OnPropertyChanged();
            }
        }
        public Paper_TestQuestion_Task_StepModel Model
        {
            get
            {
                return new Paper_TestQuestion_Task_StepModel()
                {
                    Id = this.Id,
                    TaskId = this.TaskId,
                    OperateId = this.OperateId,
                    Parameter = this.Parameter,
                    Score = this.Score,
                    SysType = this.SysType,
                    TaskType = this.TaskType,
                    Describes = this.Describes,
                    DevicetypeId = this.DeviceTypeId,
                    DeviceId = this.DeviceId,
                    StepContent = this.StepContent,
                    Prerequisite = this.Prerequisite,
                    KeyWords = this.KeyWords,
                    TimeOut = this.TimeOut,
                    Duration = this.Duration,
                    IsContinued = this.IsContinued ? "1" : "0",
                    RoleId = this.RoleId,
                    UIOrder = this.UIOrder,
                    MutexStepId = this.IsMultStep ? 1 : 0,
                };
            }
        }

        public TestQuestionTaskStepViewModel()
        {

        }

        public TestQuestionTaskStepViewModel(Paper_TestQuestion_Task_StepModel model)
        {
            this.Id = model.Id;
            this.TaskId = model.TaskId;
            this.OperateId = model.OperateId;
            this.Parameter = model.Parameter;
            this.Score = model.Score;
            this.SysType = model.SysType;
            this.TaskType = model.TaskType;
            this.Describes = model.Describes;
            this.DeviceTypeId = model.DevicetypeId;
            this.DeviceId = model.DeviceId;
            this.StepContent = model.StepContent;
            this.Prerequisite = model.Prerequisite;
            this.KeyWords = model.KeyWords;
            this.TimeOut = model.TimeOut;
            this.Duration = model.Duration;
            this.IsContinued = model.IsContinued == "1" ? true : false;
            this.RoleId = model.RoleId;
            this.UIOrder = model.UIOrder;
            this.IsMultStep = model.MutexStepId == 1;
        }
    }
    public class NotifyPropertyChanged : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged 接口实现
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propName = null)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
        #endregion
    }

    public class BoolVisibleConverter : IValueConverter
    {
        public bool Reverse { get; set; }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (Reverse)
                return (bool)value ? Visibility.Collapsed : Visibility.Visible;
            else
                return (bool)value ? Visibility.Visible : Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (Reverse)
                return (Visibility)value != Visibility.Visible;
            else
                return (Visibility)value == Visibility.Visible;
        }
    }

}


